Cannot Use Custom Emojis On Discord.py - discord

Getting Error When Using Custom Emojis In Discord.py
import discord
from discord.ext import commands
client = commands.Bot(intents=intents,command_prefix="$")
#client.event
async def on_message(msg):
if msg.author == client.user:
return
else:
await msg.channel.send("<:doory_fruit:1062084428228206657>")
client.run("MyToken")
error 1 when not inputting the id:
Image Link
error 2 when using name and id :
Image 2 Link
Any Help

Related

AttributeError: 'Message' object has no attribute 'send' when trying to send embeds using discord.py

Trying to use discord.py and learning the beginnings of bot developement, but when I try to send an embed, it gives me the error.
I tried:
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print(f'Logged in as {client.user}')
#client.event
async def on_message(message):
if message.content.startswith('!test'):
embed=discord.Embed(title="title", color=0x13fa07)
embed.add_field(name="name1", value="value1", inline=True)
embed.add_field(name="name2", value="value2", inline=True)
embed.set_footer(text="bot test 0.1")
await message.send(embed=embed)
client.run('token here')
(token ofc censored)
but then it returns
AttributeError: 'Message' object has no attribute 'send'
Welcome to discord.py, just as the error says 'Message' object has no attribute 'send' but it does have the attribute channel which has the method send that you are looking for docs
...
await message.channel.send(embed=embed)

Is Discord User Id too big to send dm too?

I'm making a slash command that can send dms to a specific user id that's been determined by a command argument. It works for specific user ids, but not all of them, including mine my alt account. Is it some permission thing or is the user id out of range?
My code
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = bot.get_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
When I input an ID that doesn't work it gives me this traceback
AttributeError: 'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Rayan\source\repos\DBot\DiscordBot\lib\site-packages\discord\commands\core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "c:\Users\Rayan\source\repos\DBot\main.py", line 56, in send_message
await user.send(message)
AttributeError: 'NoneType' object has no attribute 'send'
Help is greatly appreciated! Thank you!
I do not think the issue is that the ID is out of range. It's simply that the user is not in the cache.
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# importing environmental vars
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
APP_ID = os.getenv("APP_ID")
PUB_KEY = os.getenv("PUBLIC_KEY")
GUILD_ID = os.getenv("GUILD_ID")
GENERAL_CHAN_ID = os.getenv("CHANNEL_GENERAL_ID")
#finished importing .env vars
intents = discord.Intents.all()
activity = discord.Activity(name="being awesome losers", type = discord.ActivityType.streaming)
bot = discord.Bot(intents=intents, activity=activity)
#bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
#bot.slash_command(description="sends message to someone still testing",guild_ids=[GUILD_ID])
async def send_message(ctx, user_id: str, message: str):
user = await bot.fetch_user(int(user_id))
await user.send(message)
await ctx.respond("Message sent successfully!", ephemeral = True)
#bot.event
async def on_message(message):
channel = bot.get_channel(956302622170701946)
if message.content.startswith("help"):
await message.author.send('👋')
bot.run(TOKEN)
This will always fetch the user and therefore will be able to DM everyone, even not in the cache.

Error with discord bot 1.7.3 giving very long error

I was trying to make a discord chat bot but I got this error I am not sure what to do by the way I am using discord 1.7.3 here is the code by the way the DISCORD KEY and OPENAI-KEY are not the problem those are to hide my openai key and discord bot key:
import discord
import asyncio
import openai
import os
openai.api_key = os.environ.get('OPENAI-KEY')
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$chat'):
response = openai.Completion.create(
engine="davinci",
prompt=message.content[5:],
max_tokens=100,
temperature=0.9,
top_p=1,
n=1,
stream=False,
logprobs=None,
stop=["\n"],
)
await message.channel.send(response['choices'][0]['text'])
client.run(os.environ.get('DISCORD-TOKEN'))
Here is the error I am getting:
import discord
import asyncio
import openai
import os
openai.api_key = os.environ.get('OPENAI-KEY')
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
elif message.content.startswith('$chat'):
response = openai.Completion.create(
engine="davinci",
prompt=message.content[5:],
max_tokens=100,
temperature=0.9,
top_p=1,
n=1,
stream=False,
logprobs=None,
stop=["\n"],
)
await message.channel.send(response['choices'][0]['text'])
client.run(os.environ.get('DISCORD-TOKEN'))
Here is the error I am getting
Traceback (most recent call last):
File "c:\Users\Private\OneDrive\Desktop\Pro\GitHub Repo\Discord_chat_bot\Bot.py", line 35, in <module>
client.run(os.environ.get('DISCORD-TOKEN'))
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Private\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
I was expecting for it to work if I try this code in 2.0.0 discord it give a different error
The reason I am using 1.7.3 not 2.0.0 is because I had a different error and to fix it I had to switch to 1.7.3
Error on this line:
client.run(os.environ.get('DISCORD-TOKEN'))
The token you are passing in is None because os.environ.get('DISCORD-TOKEN') returns None.
You could have forgot to set your environment variable or you had it in a .env file. If you have it in a .env file, please load it:
from dotenv import load_dotenv
load_dotenv()

Discord.py Cogs cooldowns?

I have a problem, when I try to build a cooldown "handler" into a discord.py cog, it sends the message etc., but the cooldown message is still sent and the cooldown doesn't work either.
I've tried everything, but I really can't get any further...
Hope someone has a solution!
Thanks in advance
import discord
from discord.ext import commands
import asyncio
import time
import json
import random
import typing
from colorama import Fore, init
from datetime import timedelta
from discord.ext.commands.cooldowns import BucketType
from discord_components import DiscordComponents, Button, ButtonStyle, Select, SelectOption
init()
with open('config.json', 'r') as f:
config = json.load(f)
prefix = config["prefix"]
token = config["token"]
class Fish(commands.Cog):
#commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.message.delete()
sec = round(error.retry_after)
td = str(timedelta(seconds=sec))
x = td.split(':')
em = discord.Embed(title=f"Yo, chill and wait {x[0]}h, {x[1]}m, {x[2]}s!", color=0xf1c40f)
em.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
await ctx.send(embed=em, delete_after=30)
#commands.cooldown(1, 60, commands.BucketType.user)
#commands.guild_only()
#commands.command(aliases=["f"], description='Fish some fishes', help="f")
async def fish(self, ctx):
#code
def setup(client):
client.add_cog(Fish(client))```
I know the answer!
In the on_message method there was the
await self.client.process_commands(message)
because of this, the bot sent 2 messages every time!

Link to the meme in Discord.py Meme command

I am making a bot in discord.py and have made a meme command using AIOHTTP. I want the embed title to be the link to the meme and the footer should show the upvotes and all that stuff like in the screenshot.
Here is the code
#client.command(aliases=['memes'])
async def meme(ctx):
embed = discord.Embed(title='Meme', description=None)
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/wholesomememes/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed, content=None)
```
replace it with this code
Toutorial
step 1: install praw (pip install praw)
step 2: go to https://www.reddit.com/prefs/apps create app
step 3: copy client_id and client_secret
step 4:run bot
#bot.command()
async def meme(ctx):
reddit = praw.Reddit(client_id='clientidhere',
client_secret='clientsecret',
user_agent='python')
memes = reddit.subreddit("memes").random()
await ctx.send(memes.url)

Resources