#discord-bots
1 messages · Page 861 of 1
bruh
What does the linter say when it complains about defaulting to Nond
yes
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
but thats the users permission in the text channel they are in?
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
nah it doesnt
well there is ctx.author.guild_permissions but it returns as permissions value
!d disnake.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.GuildChannel.permissions_for "disnake.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
isn't permissions a tuple?
looks something like
[(administrator, False), (connect, True)]
yea but it returns in a disnake.Permissions.value
idk why its doing that
Its repl.it
Ok and?
He can't send it in full
Why?
ye you have to do ```py
ctx.author.guild_permissions.send_messages
so @slate swan you can do something like this to check the authors permissions
kek
can anyone guide me on how to make a bot notify when a streamer goes live on, say, Youtube/twitch
well first, you can use both the twitch and youtube api to figure out if the streamer goes live, then use a db to store that streamer’s id then make a command for it to say when the streamer is online
check stream often and when its live send msg to discord and set a variable like live=1 and set it live=0 when its found offline again this helps prevent it spam when it checks stream that its live after each time it still live etc...
so bot will only alert if live=0 and stream is live
why db?
that's nessecary?
myself uses database and has a column live wich i set 1 or 0 and updates this depend if its online or offline and when it had 0 and puts 1 it sends to discord
^
it’s optional but it’s gonna be more helpful
i other hand has alot of streamers and uses dlive twitch youtube
so I use requests right?
there's no module for this?
no.
requests is blocking
if anything, use aiohttp.
it’s made for async projects
aiohttp
i mean it'll have concerning ratelimits
bots do not have access to the search feature on discord for one
maybe it puts the message count in a db
im not sure the best way but you can look through the source of python bot to try to see what it does
yeah python bot uses a database
online = len(list(filter(lambda x: x.status == discord.Status.online, mbrs)))
print(f"{online}")
idle = len(list(filter(lambda x: x.status == discord.Status.idle, mbrs)))
offline = len(list(filter(lambda x: x.status == discord.Status.offline, mbrs)))
dnd = len(list(filter(lambda x: x.status == discord.Status.dnd, mbrs)))
Shows the wrong number of people on the server (by status)?
intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@spring flax The team is in cogs, should I write intents there?
yeah that's likely the best way though
no do it in your main file for bot construction
not sure if you saw it or not but bots can't use the search feature
and no i don't think it'd be that buggy
What?
what?
in main.py there are intents, but in serverinfo cogs, it doesn't show correctly there?
is thear a way i can send a message in a chat when some add the bot like the guild id
what are yor intents?
i mean big db's like postgres will be able to handle that with ease, and using it asynchronously should work fine
!d disnake.on_guild_join
disnake.on_guild_join(guild)```
Called when a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild") is either created by the [`Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") or when the [`Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") joins a guild.
This requires [`Intents.guilds`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.guilds "disnake.Intents.guilds") to be enabled.
ty
🤷♂️ but maybe try making a whole new connection just for that if you think its slowing down
whats the difference between bot.command and command.comm and?
Defult intents
bot.command is for main file and commands.command is for cogs
how do i do pagination in buttons?
idk depends on what u are doing
how can i make it send a message if an emoji is reacted with? I cant put await inside of a check, and i cant async the check otherwise it doesnt read the emoji reaction...
using discord.py
why do you have ctx.bot?
uhh im not sure, i used the template from the docs, should i remove the bot?
its just bot not ctx.bot so yes remove it, and the check function is really wrong, the check function is for checking if the reactions are from the list and the user is the author
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('👎')
else:
await channel.send('👍')
``` look at this example
i have multiple emojis that i want to do different things based on which emoji was reacted with
so you have to do something like this
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in list_of_emojis
yea so check which emoji they reacted with and then make if statemnts under the wait_for
instead of just making them in the check function
put the if statements inside of the try:?
yes inside the try and under the wait_for
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
#if statements
uh, how do I upload animated emojis 
so this works when i say it but i want others to say it and it will also reply to them@bot.event async def on_message(ctx): if ctx.content == "Hello": await ctx.reply("Hey!")
why does it only listen to me?
hi
I did that and now the bot wont print if the emoji is reacted with, and the user in the try is not being used..
is there one? I dont think so
disnake.on_invite_create(invite)```
Called when an [`Invite`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite "disnake.Invite") is created. You must have the [`manage_channels`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_channels "disnake.Permissions.manage_channels") permission to receive this.
New in version 1.3.
Note
There is a rare possibility that the [`Invite.guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.guild "disnake.Invite.guild") and [`Invite.channel`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.channel "disnake.Invite.channel") attributes will be of [`Object`](https://docs.disnake.dev/en/latest/api.html#disnake.Object "disnake.Object") rather than the respective models.
This requires [`Intents.invites`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.invites "disnake.Intents.invites") to be enabled.
I usually use the member id, xp, level, guild id, number of infractions, etc
whaaa 
but for my new bot, I am handling infractions differently
print reaction
I’m making a separate infractions table with all the information of an infraction that include infraction id, target id/name, issuer id/name, etc
I use a helper infractions file to handle all this stuff
what do you mean?
and I’m my infraction class are methods to grab infraction, show expired infractions, etc
put print(reaction) after the wait_for
so this works when i say it but i want others to say it and it will also reply to them@bot.event async def on_message(ctx): if ctx.content == "Hello": await ctx.reply("Hey!")
why does it only listen to me?
the same way you make normal emojis i think
Like I convert the animated image to Bytes and stuff, but when I use the create_custom_emoji method, it just returns unsupported image type, it works for normal images though

on_message doesn’t take ctx
@kindred epoch
I’m going to work on that one. I might just make the infraction id column auto increment
The Bot will only respond to me but i want it so it responds to other people @bot.event async def on_message(message): if message.content == "Hello": await message.channel.send("Hey!")
generating a long random number might be interesting when an infraction is created
you do know that you can name the parameter anything
@slim ibex see it works when i say Hello but if you were to say it it wouldnt work
is it possible to make the bot say something every specific day?
I also use an enum to classify infraction severity
class InfractionType(Enum):
NOTE = 0
WARN = 1
…
@slate swan
so every 25th of feb etc it says something?
doesnt print anything, and the user variable is not being used, could it be ignoring my reactions because it thinks im not the author?
🗿but just put message as that’s what docs say
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'HelpCommandDropdown' object has no attribute 'ctx'
yeah enums are helpful
are you using the command and reactiong?
docs
self-implementation
mind you, this bot I’m making is for a single server lmao
yes
no idea then
thanks
I might be overdoing it but, I can use these features if I ever make another bot I intend to distribute to multiple servers
the response time below is not discord bot api response time btw
how to purge messages of a specific user?
anyone
try changing reaction.emoji to str(reaction.emoji)
in the if statements? ok
!d discord.TextChannel.purge takes a check kwarg, you can use a lambda for this
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
yes
nope, still nothing, it just times out
mhm, I want to make a user command using disnake which will purge for a specific user
remove user and change bot to ctx.bot in the wait_for
like i said before, the user in the try is not being used either...
ok let me try that
printed the whole reaction, so it reaches the print(reaction) in the try but doesnt go to the if statements
i will try removing the str()
yeah nothing, still doesnt go to the if statement after that
hm
can you show me ur current code
You might have to str(reaction.emoji)
!d discord.Reaction.emoji
The reaction emoji. May be a custom emoji, or a unicode emoji.
let me try that again, i had done str(reaction.emoji) then removed it a few mins ago because it still wasnt working
nope, just returns the emoji AKA print(reaction)
instead of printing reaction, can you print reaction.emoji?
you have to put the if str(reaction.emoji) outside of the try:
doesnt print anything
wtf
The Bot will only respond to me but i want it so it responds to other people @bot.event async def on_message(message): if message.content == "Hello": await message.channel.send("Hey!")
nope, still doesnt do anything
huh?
doesnt print anything
oh no sorry
i made an error i will correct it
str(reaction.emoji) == 'your emoji'```
put that before the try
it is before the try..
???
then show the entire code please
it checks the reaction if you don't know
thats literally what he has
entire code
ok thanks
paste the command code so we can see it
yeah
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Oh
dont post your discord bot token
you have to put three ` before and after the code
you should keep the token in a seperate file and read it btw
import discord
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('@alpine bobcat'):
await message.channel.send('Hello! My prefix is +.Command list +help')
client.run('token')
On replit he worked
are you getting any error?
No,he just not work
ok...
yep, thats what your code is looking for
yes
I type
message.content.startswith checks if the message starts with it
ok
try replacing @alpine bobcat with anything else to check if it works or not
i think what they are trying to do is if the bot gets mentioned, it replies with the prefix and help command, correct?
Is it allowed to make a music bot?
yes
Still doesn't work
hmm
o, ok but rythem and groovy why dead?
Yes
do you have everything installed (like discord.py)
i think because youtube forced the devs to take it down
import discord
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('Hi there!'):
await message.channel.send('Hello! My prefix is +.Command list +help')
client.run('token')
with this if you type Hi there! it should respond, try doing that to make sure it responds
because rhythm and groovy were making a profit, with their subscriptions
Ahha thanks
yeah this should work @slate swan
you can if you want
everyone has a different opinion
does it work? yes it does, so its not "wrong" to use it...
Client is soooooo old
and?
i define by bot var as bucko
lmao
yeah but using client can be good for beginners
any ideas btw?
no?
i looked for errors, but i did not find any errors
Error
oh
so that means discord.py is not installed
replit has discord.py by default, that's why it didn't work
He installed
theres an invisible character after that parenthesis that you need to remove
its a unicode character error, it detects a space after that
yeah, on your client.run() there is a space after the closing bracket ) delete the space
He's gone
try running again
Error
show your error please
Bot turned on
mobile programmer 🦾
But commands not work
are you getting a error message
No error , commands just not work
yes but you wont get help about youtube here duo ToS but hell yeah musicbots allowed
.-.
@slate swan did you copy that code?
oh
Yes
token is incorrect
that means that the token is not correct
wrong token
then why no work 
What’s wrong?
it doesnt filter which reaction was reacted with
Show code
ctx.bot.wait_for??
so in my code the if str(reaction.emoji)is outside of the try
was told to test it like that lol, let me remove the ctx and try again
Do reaction, user = .... reaction is a tuple if you do it like that
oh yeah
Thanks .
why?
you need await bot.wait_for
still doesnt work after removing ctx
no problem
it just times out
@lost lichen
where is reaction, user = i dont see it
reaction_add takes reaction and user
??
uhhh what...?
he is saying to add it lmao
When you do ur wait_for
its already adding the emojis
see here it shows 2 ppl reacted, one is the bot the other is me
the reaction_add event doesn’t take in what you specified in your wait_for
.
i know
my issue is not adding the reactions
my issue is running something when one of those emojis is reacted with by the user
in this case, a simple print()
mate, you do realize that ```py
reaction = await bot.wait_for("reaction_add", ...)
^
and you are using an "emoji" attribute on a tuple
^
how to remove the delay in sending a command?
huh??
str(reaction.emoji)
what exactly do you mean?
the tuple has no attribute of emoji
so how would i do it? remove the str()? because i did that too
im getting html kind of error when im running my repl, is my bot rate limited?
The response from the bot is sent too slowly
oh
reaction, user = ...
probably yes
ok thanks
that would probably be because you are running it on android and mobile is slower and/or internet like justarandom said
that is due to internet or servers being slow
you can't really make it faster
^ slow IDEs/OSs can slow your bot
sometimes
this also
How?
low bandwidth
File "main.py", line 110
@bot.command()
^
IndentationError: unexpected unindent
help
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
No need to send it again
that means you have a space or indent
that should not be there
there is none
How do i change my discord py bot version? (i want to go from rewrite to previous versions)
maybe you forgot to close a parenthesis or something
try:
reaction, user = await bot.wait_for('reaction_add', timeout=15.0, check=check)
```? because before i was told to remove the `, user` lmao
since user was not being used or something
you can not make it faster
yes
you need user if you want to access a user iirc
Sad
yeah
Did someone try to make a bot what you can listen to a radio in a voice channel with?
yeah, you could just do ```py
reaction = ...
if str(reaction[0].emoji) == ...:
...
idk
but the other way is more readbable
but all are closed
ok...
error doesn't lie
yeah
still doesnt do anything
could you show your code?
hmm
just times out
ok sir
show code
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
oh
you just need to paste your code
or paste your code an put three ` before and after the command
code @red nest
ok i'll take a look
ok sir
so you are sure that there is no space
because that's what i would say
man im kinda dumb
why?
for coding python
errors?
?
did u react
i said im an idiot for coding python
this is also running in a cog btw
soo i might miss something
yes i did
ok...
how do i check in on message if someone sent a mp3 file ?
and get its url ?
which emoji?
soo no problem with code?
js?
i didn't find any but the error is saying that there's a space
yeah
or is it the problem of the command count?
!d discord.Message.attachments message.attachments[0].url maybe
A list of attachments given to a message.
@oblique adder
the if str(reaction.emoji) needs to be outside of the try
hmm
ill change position of command timerhelp
lemme check if that works ig
sed
no success
ok
it blames the command under timerhelp
ok
still doesnt work...
mine too XD
don't know
hmm
the fact my code was working perfectly before, i just couldnt send a message, and everyone here told me to change my whole check function 
oh so it has to do something with the check
i dont know.
lol what
this WAS my code before, my problem was i couldnt put await ctx.send, but it would print the colour based on the reaction pressed perfectly, lmao
does message.content return none if there is only files ?
ignore this just tryna find general
Hi
trying to figure out why ctx.send does not work
OHHHH
i figured it out
so you see, when i had it setup like that screenshot, you cant put await inside of a check function, and you cant async the check function either bcecuase otherwise it just doesnt function
yeah
File "main.py", line 111
@bot.command()
^
IndentationError: unexpected unindent
help anyone?
unexpected unindent
like i said, there is a space or something
but ther isnt one
errors don't lie
so... how would i have made it send the message and accept only 1 reaction?
lol
Ping me
ik but, check my code :https://paste.pythondiscord.com/gupuzupohi
it works with multiple reactions
i made a rock paper scissors command with that and it works
no way bro u gunna hack us
Im lagging
could you send the code please?
something like this ``` valid_choices = ["🪨", "📰", "✂"]
ai_choices = ["Rock", "Paper", "Scissors"]
ai_choice = random.choice(ai_choices)
embed = discord.Embed(
title='Rock Paper Scissors',
description='React with the emojis to play',
color=discord.Colour.random()
)
embed.set_footer(text="Rock Paper Scissors Game")
msg = await ctx.send(embed=embed)
await msg.add_reaction("🪨")
await msg.add_reaction("📰")
await msg.add_reaction("✂")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_choices
try:
reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
#i added that for debugging some code but i'm too lazy to delete that
print("reaction passed")
except asyncio.TimeoutError:
return await ctx.send("Not fast enough my guy!")
if str(reaction.emoji) == "✂":
if ai_choice == "Rock":
await ctx.send("HAHAHAHA! I SMASHED YOU WITH MY ROCK!")
elif ai_choice == "Scissors":
await ctx.send("Tie! No one wins! We both chose this red thing right here: ✂")
else:
await ctx.send("Nooooooooo... You got me with your scissors")
if str(reaction.emoji) == "🪨":
if ai_choice == "Paper":
await ctx.send("Yes! I packed your rock into paper!")
elif ai_choice == "Rock":
await ctx.send("Tie! No one wins! But why did we try to fight ourselves with the same thing?")
else:
await ctx.send("WHAT? HOW DID YOU JUST SMASH ME?")
sleep(0.1)
await ctx.send("aimbot")
sleep(0.1)
await ctx.send("hacker")
i checked the code its not a hack
You on the hack?
Imagine hacking with discord.py
so im trying to make a slowmode command. im using pycord, here's my code
@slash_command(guild_ids=[918349390995914792], description="slowmode")
async def slowmode(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Slowmode set to {seconds} seconds.")
``` this is inside a cog called `Fun`
when i use it it raises an error
```Application Command raised an exception: TypeError: Fun.slowmode() got multiple values for argument 'seconds'``` any help would be appreciated
bruh
thats the official python discord pastebin lol
yeah
line 3, in <module>
from help_cog import help_cog
ImportError: cannot import name 'help_cog' from 'help_cog'```
Why isn't it importing
Idk man I don’t trust any link
why you on the internet
you can trust that link it's not a hack
What arenu trying to do
it got multiple values for argument “seconds” m’bro hope that helps
yeah but i passed 10
import discord
from discord.ext import commands
import os
#import all of the cogs
from help_cog import help_cog
from music_cog import music_cog```
so idk why thats happening lol
Is it possible to use json file as a list of sorts?
valid_choices = ["🪨", "📰", "✂"]
ai_choices = ["Rock", "Paper", "Scissors"]
ai_choice = random.choice(ai_choices)
embed = discord.Embed(
title='Rock Paper Scissors',
description='React with the emojis to play',
color=discord.Colour.random()
)
embed.set_footer(text="Rock Paper Scissors Game")
msg = await ctx.send(embed=embed)
await msg.add_reaction("🪨")
await msg.add_reaction("📰")
await msg.add_reaction("✂")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_choices
try:
reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
#i added that for debugging some code but i'm too lazy to delete that
print("reaction passed")
except asyncio.TimeoutError:
return await ctx.send("Not fast enough my guy!")
if str(reaction.emoji) == "✂":
if ai_choice == "Rock":
await ctx.send("HAHAHAHA! I SMASHED YOU WITH MY ROCK!")
elif ai_choice == "Scissors":
await ctx.send("Tie! No one wins! We both chose this red thing right here: ✂")
else:
await ctx.send("Nooooooooo... You got me with your scissors")
if str(reaction.emoji) == "🪨":
if ai_choice == "Paper":
await ctx.send("Yes! I packed your rock into paper!")
elif ai_choice == "Rock":
await ctx.send("Tie! No one wins! But why did we try to fight ourselves with the same thing?")
else:
await ctx.send("WHAT? HOW DID YOU JUST SMASH ME?")
sleep(0.1)
await ctx.send("*aimbot*")
sleep(0.1)
await ctx.send("*hacker*")
ignore its just so i can read it better
“What? How did you smash me?” Sounds gpkinda sus man
dont use time.sleep
im not, thats not my code lmao
why
@nimble plume
ah sorry
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
oh yeah, if you do sleep it will stop the rest of the code, thats why you have to async it
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_choices
try:
reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
except asyncio.TimeoutError:
return await ctx.send("Not fast enough my guy!")
if str(reaction.emoji) == "🪨":
your code```
you should use asyncio.sleep not time.sleep
it will block all of your code and making your bot not acknowledge a heartbeat so it will get disconnected from the websocket and from the api
you see, thats what i have lmao, im going insane omfg
oh ok
yeah but it works fine for me
how do i send an image in an embed
link or file, let me get an example hold on
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
cuz this is what it is doing rn
exactly embed.set_image()
ok thanks
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'timeout'
what should i do to fix this i am using discord.py
picture = <picture you want>
embed = discord.Embed(title=f'Picture:', colour=0x400080)
embed.set_image(url = picture)
await ctx.send(embed=embed)```
someone help me with this
show code
you dont import cogs you load them
what do you mean
send us your code.
you make a global setup method and you load the cog
!d discord.ext.commands.Bot.load_extension
load_extension(name, *, package=None)```
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

button = Button(label="Invite", style=discord.ButtonStyle.primary,timeout=seconds)
code should work regardless of who runs it
hi, is there any way to set multiple images in embed? I have seen recently that link embeds are having multiple images is it possible through bot?
because you dont set the timeout there lol
from the looks of it, timeout is not a kwarg supposed to be there.
yeah
maybe because im running it in a cog??
idk
you can have multiple images but im sure theres a limit as well, just like the amount of characters in a embed.
maybe
oh
im not sure about that tho
but that shouldnt affect it lmao, ugh why doesnt it wanna workkk :(
whats happening?
when running the command and reacting, it wont print or do anything based on what emoji was reacted with, it just times out
response time is not discord bot api response time btw
@red nest i removed count command and now it works
and im running this in a cog
tbh i dont know because i dont use emojis as buttons and i actually use buttons so i recommend you use buttons if you want a fork thatd close to dpy i would use disnake which has a guide on how to migrate and has examples for buttons
discord.py has buttons iirc, doesn't it?
what is bot exactly
2.0 yes
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
main does have buttons but doesn't have other new features like timeout
alr
it wont work because you have 2 instances of your bot
what do you mean
in your class initiate you pass your bot instance
why does this always say unsupported image type whenever I try to add an animated emoji, it works with a normal one though ;-;
async with aiohttp.ClientSession() as ses:
async with ses.get(image_url) as r:
img_or_gif = BytesIO(await r.read())
b_value = img_or_gif.getvalue()
if r.status in range(200, 299):
await inter.guild.create_custom_emoji(image=b_value, name=emoji_name)
if i remove the bot = what should i put here in the wait_for then??
yeah
no you make a class variable thats the bot in params
is it a gif?
i recommend you send the img first to see how it looks
yeah
sorry, what do you mean by this
lemme try using a different link then
😔
class Dog:
def __init__(self, arg):
self.arg = arg
here youre making a class variable or an attr
how can i get only the video urls in channel history
That's an instance variable not class
i ment it like its a variable bound to a class lol
Nop variable is bound to the instance of the class
class Dog:
arg = 5
That's bounded to the class
bro i ment it like you cant use it outside of any instance of the class
so, im still confused on how to get my code to work, what do i need to class, how do i class it? i am not familiar with classes in python
alr lol
you have a point
it converts all the stuff but doesnt upload it 
oof
👀
can anyone help me?
oh
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
!d filter
filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.
Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.
See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
Murder she wrote!!
Guys I wanna put a huge part of my code into another file to use it how would I do that? (Discord.py)
wut
!d discord.utils.find
discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
cogs
who? 
at that's it
Huh
I was talking to Soop
help me too, please hun
with?
async def jpg_File(message):
channel = bot.get_channel(699577970117050399)
messages = await channel.history(limit=None).flatten()
for p in messages:
print(p.attachments)```this extracts images and videos
as @maiden fable stated you can iterate through the channel history and check for video urls in each of the messages
@maiden fable 
I'd recommend using regex to match the video urls in the message content
wait what is the error?
sadly i dont know how to do that
Yea regex sucks ik
'unsupported image type'
getbuffer() instead of getvalue()
Thankfully big brain peeps did most of the painful regex for us. If you make a quick google search you can "regex pattern to match links". The problem is, how do you differentiate between an image or video link I don't know how to do that
ah lemme see
It would be much easier if you were just checking for uploaded videos not links that point to videos
Just check if the most common image formats like png, jpg, jpeg and stuff are in the url string?
Well you see most links don't end in png or mp4 etc
if "png" in url
For example a youtube link , I mean the user knows that all youtube links "can" be videos, but some can be of channels so that's a problem.
Ah that way
That's assuming that the word png will actually be in the url
Wait I thought only user uploaded vids and stuff
If it's random vids then it's problematic but if all the vids follow a strict format you can get all of em
Yea
Nope person said video urls
So I'm assuming it's links
Ah okay (Sleepy asf rn, already 12 here)
I'm trying
I mean, u just gotta change half a line 👀
show code
mhm
show whole traceback. u ain't using a startswith anywhere
rip, i gotta print the traceback, brb
Smh just do raise error
no
bruh
she just tryna mess with my brain rn
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.

what is the extension of the image file
idk, this is the link though - https://tenor.com/view/anime-blushing-girl-blonde-i-dont-like-gif-12347992
embed failure
Bro, u need the link of the actual gif
I'm being dumb, alright
i forced it to not embed S.M.H.
Stop the cap

!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Indeed
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
show yr code again
mhm
with?
i need help aswell
Don't use time.sleep() it's blocking
@final iron could i get help?
Don't ask to ask
What help?
i know but the bot stop working when he is on the loop
my problem is at the end on the code, if name == "main":
bot.run(TOKEN)
it does not work
if name == main:
bot.run(TOKEN)
wait somthing is wrong with this: bot.run(TOKEN)
should i paste my discord bot token in there?
ofc
whatever you're trying here is very basic and will lose progress once the bot restarts, just saying
@halcyon onyx
put bot.run in a main function, and run that main function in the if-name-main idiom
My bot restarts 5 times. What could be the reason?
your code
just convention pretty sure
how
don't tell me you're using replit as hosting
no
oky
I host the bot through my device
can anyone help me
Then you should be fine, any errors?
How do you know / why do you think so?
does anyone know how to save user data in discord.py after you stop running your IDE?
Use a database
Wdym
A database
A database stores data for you locally or in the cloud… can’t be said more
Like sqlite3
well, I have a code with on_ready and when the bot starts, it displays a message saying that the bot will start soon
Yes, but an async wrapper
!pypi aiosqlite
Don’t do stuff in on_ready tho, a simple print at most
can anyone help me please i have 1 error, its says: name 'name' is not defined
how do i do that?
Define name
Define name
in vsc terminal?
Define name
or cmd
In your code
It's __name__
I only have this codepy @bot.event async def on_ready(): print('Бот скоро будет запущен') await bot.change_presence(status = discord.Status.online, activity = discord.Game("h!хелп")) for guild in bot.guilds: for member in guild.members: users = { "member_id": member.id, "guild_id": guild.id, "name": member.name, "money": 0 } if collection.count_documents({"member_id": member.id, "guild_id": guild.id}) == 0: collection.insert_one(users)
still dosent work @final iron
if __name__ == "__main__":
...
Don't try to make requests to the api in your on_ready
The api can disconnect you
test]
@final ironin name write the name of the bot file?
No
just copy and paste it?
Not exactly
name is a function from python
But the if __name__ == "__main__": part
@bot.command()
async def alex(ctx, arg):
name, leng, amnt = arg.split(':')
users = 0
content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
buffer = BytesIO(content.encode('utf-8'))
file = discord.File(buffer, filename= name)
users += 1
print(f"{user} | {users}")
ctx.send(file=file)``` discord not defined but it should from module?
Can i get som help: File "C:\Users\sweti\OneDrive\Skrivbord\swishbot\swishbot\main.py", line 50, in <module>
bot.run(TOKEN)
bot.run(TOKEN) what should i do ?
You need to make token a string
you should take the token of the bot from https://www.discord.com/developers
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Do bot.run(“bot.token”)
And change bot.token to your bot token from the link @mystic vault sent
If did not make a bot from there make one and copy its token, and if you want to invite your bot to an server, use URL Generator option in the bot profile, click on bot option, then copy the link that will be on the bottom
^ @kind cargo
yes
Read what he said
alright
Don’t do API calls in on_ready, use a startup task instead
@maiden fable i figured it out btw
@kind cargo https://discord.com/developers/applications
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Create application
how
@bot.command()
async def ping(ctx):
await ctx.send("|| Boomer ||")
@bot.command()
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))
i took every attachment ever sent in the channel and converted it into a list then just did this for i in a: if i.endswith("mp4\n"): print(i)
That won't work everytime @left crater
@slate swan i didnt understand
Since sometimes there is a \ at the end too
Yes
You need to define bot
could we go call or pm @slate swan
U should use if "mp4" in url
now i have 1600 urls
but i have a slight problem
@potent spearokay thx
No he should use mimetypes
tf is that
there is spaces in between them
will that still send
thanks for the help
mimetypes is a global way to check a files type. So if i were to rename a mp4 to mp3 mimetypes would still identify it as a mp4
Ah okay
@bot.command()
async def alex(ctx, arg):
name, leng, amnt = arg.split(':')
users = 0
content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
buffer = BytesIO(content.encode('utf-8'))
file = discord.File(buffer, filename= name)
users += 1
print(f"{user} | {users}")
ctx.send(file=file)``` discord not defined but it should from module?
Can you send the traceback?
it didn't work...
Who me?
Yes
is there anyway i can remove all of these spaces?
the line breaks?
ye
👀
Is this created by code? Or a file???
code
i used a for loop to get all those links out
Could you show the code?
for i in a:
if i.endswith("mp4\n"):
print(i)```
print already has as default a \n
You can remove \n in the list or modify the print function.
a = [links.mp4\n, link.mp4\n]
for i in a:
if i.endswith("mp4\n"):
print(i, end='')
!d print
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)```
Print *objects* to the text stream *file*, separated by *sep* and followed by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like [`str()`](https://docs.python.org/3/library/stdtypes.html#str "str") does and written to the stream, separated by *sep* and followed by *end*. Both *sep* and *end* must be strings; they can also be `None`, which means to use the default values. If no *objects* are given, [`print()`](https://docs.python.org/3/library/functions.html#print "print") will just write *end*.
The *file* argument must be an object with a `write(string)` method; if it is not present or `None`, [`sys.stdout`](https://docs.python.org/3/library/sys.html#sys.stdout "sys.stdout") will be used. Since printed arguments are converted to text strings, [`print()`](https://docs.python.org/3/library/functions.html#print "print") cannot be used with binary mode file objects. For these, use `file.write(...)` instead.
Look at the "end" kwarg default is \n with this code we just set it to a blank string.
Can bots use server emojis in their status?
Have you imported discord?
oh wait
can i get some help
I can just test
learning basic python can help
So learn basic Python and try building a Discord bot when you're more comfortable
okk
Unfortunately, it's hard for us to help you when you're finding it hard to debug NameErrors.
We expect you to have a basic knowledge of Python.
Quick question, is there a way to make a new cooldown inside a command(im not talking abt @commands.cooldown()). Special cooldown for special ppl :)
Yes
What kind of cooldown? Can you elaborate? Because chances are that @commands.cooldown() can help with it.
Can you show your code?
I mean i want to ctx.command.reset_cooldown(ctx) and then ill make a new cooldown inside an if statement
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
No not really, you're not being very clear.
@bot.command()
async def alex(ctx, arg):
name, leng, amnt = arg.split(':')
users = 0
content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
buffer = BytesIO(content.encode('utf-8'))
file = discord.File(buffer, filename= name)
users += 1
print(f"{user} | {users}")
ctx.send(file=file)``` discord not defined but it should from module?
What kind of cooldown do you want to implement? Do you want the ratelimit to only apply once you've reached a certain point in the command's execution? You didn't provide any further clarification.
No, the whole file.
?
like if the current cooldown is 20 and my id in a special(like premium) list, it will allows me to use the command every 10sec not(20)
list =["a list"]
if myid in list:
#reset_cooldown, and creating a new cooldown
No i want per
UGH idk how to explain it
😭
basically im using 1.7v
not 2.0
Hm.
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
Create a bew webhook?
new*
Also
Send more code, it's pretty hard to debug that without more context.
I found a stackoverflow that might be useful for you @Saad#1337
Ye sure show me
You can just visit the source code and then implement it in your app if you want.
I'm not looking forward to guiding someone through the logic of implementing something like that lol
Let me get link brb

@bot.command()
async def alex(ctx, arg):
name, leng, amnt = arg.split(':')
content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
buffer = BytesIO(content.encode('utf-8'))
file = discord.File(buffer, filename= name)
ctx.send(file=file)
how to fix this problem NameError: name 'bot' is not defined
Define bot
how ?
bot = commands.Bot(command_prefix="pls ", help_command=None)
could we go pm?
K
i have sent u
PMing is usually a bad idea
Disallows other people to help and if someone gives you bad advice theres no one there to say its bad
Try not to dm
@kind cargo just put this under imports
@slate swan
@kind cargo Also By the looks of it your not really familiar with python so I recommend docs
no
you dont make a random instance of your bot?
await ctx.send(...)
You have to await send()
He needs to define
Ok
What line
it doesnt matter?
you define it with an instance of the class not another one
To me?
You used web hook that doesn’t exist?
Yes, obviously
Check my code before answering.
Bruh
ty
I'm not asking for the line number, can you just show the line of code that failed
is it possible to have a lot of bot commands in a separate file and import them all together as extensions through cogs? or only 1 command per .py file
You can put multiple commands in a cog
Is there an easier library than nextcord regarding callbacks, and add_views? I am not so good with OOP.
online = len(list(filter(lambda x: x.status == discord.Status.online, mbrs)))
print(f"{online}")
idle = len(list(filter(lambda x: x.status == discord.Status.idle, mbrs)))
offline = len(list(filter(lambda x: x.status == discord.Status.offline, mbrs)))
dnd = len(list(filter(lambda x: x.status == discord.Status.dnd, mbrs)))
Shows the wrong number of people on the server (by status, there are intents)?
I wanna spawn those buttons based on multiple keywords. But I do not know the amount of buttons, before I query and online API. So its N amount of buttons and each needs a callback.
fits = ['1','2','3']
@bot.command()
async def tempest(ctx):
message = await ctx.send("test")
# Establish an instance of the discord.ui.View class
view = nextcord.ui.View()
for i in fits:
view.add_item(item=nextcord.ui.Button(style=nextcord.ButtonStyle.link,label=str(i),url=message.jump_url))
await ctx.send("pick a choice", view=view)
How would I know which button has been pressed?
ⁿᵉˣᵗᶜᵒʳᵈ
I am open to any other library 🙂
use disnake
nextcord has a slow rate of development and has practically only changed the namespace
I just checked the disnake example file for buttons, it shows how to make buttons if they are pre defined, but I need N amount of buttons (not hardcoded). How would I do that?
well
typically you would want to avoid this and precode it in a class, but if necessary you would do ```py
view = disnake.ui.View()
for i in fits:
view.add_item(disnake.ui.Button(
style=disnake.ButtonStyle.green,
label=str(i),
url=message.jump_url,
)
And how would you know which button has been pressed?
im not sure if you can if your button is a url button but you would have to subclass Button to add a callback method
The URL button was just an example, sorry. I do not need an URL button. After the user picked a button I want the bot to post an image.
how do i call multiple commands in a cog file
How? I did not see any example code in stackoverflow or github that shows that for N amount of buttons 😦 Maybe I just missed it
I tried to find example code for this the last few days 😛
Each view can have 5 buttons per row, and you just need logic to divide them into groups of 5
The buttons in that example are hardcoded. So the approach would not apply, would it?
load
If I run that command in a for loop, it will overwrite the same button over and over.
fits = ['1','2','3']
@bot.command()
async def tempest(ctx):
message = await ctx.send("test")
# Establish an instance of the discord.ui.View class
view = nextcord.ui.View()
for i in fits:
view.add_item(item=nextcord.ui.Button(style=nextcord.ButtonStyle.link,label=str(i),url=message.jump_url))
await ctx.send("pick a choice", view=view)
Because the buttons are fetched from a database
Unknown before how many there are and what text they contain
Until the database query, correct.
But for simplification, lets assume I use a random number to define how many buttons there are.
Correct.
Just make a lambda and map each letter in a dictionary
To a different lambda, that is
So that is why I did not find anything on stackoverflow?
Yes it would
Just set the callback argument in button to a lambda you generate each iteration
Not sure why you need a decorator as it’s just a plain function that’s called
Decorator* not callback
I "just" need the value of the button (or know which button the user has pressed). The bot decides what to do next. Or is that oversimplyfied?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
I saw on_component on stackoverflow
The Component Interaction Object
But I am terrible with classes 😛
Let there be a function async def process(label, interaction), so every iteration in your loop you’d generate a bound function async def inner(interaction): await process(i, interaction)
Assuming i is whatever the button’s label is
So forgive me, not lambdas, an async inner function 😄
And then in process you could access the button’s name
🤯
await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")
That looks similar
discord-components
Eh, idk why you’d do that
😔
I think actually parsing the discord json response would be easier for me, since I do know python (just not oop), but if for whatever reason I need to pass this code on to someone else in the future, I do not want to leave them with a mess.
Parsing json is simple, I personally don't think it would be a mess
As a general questions, which is the most commonly used library? I see stackoverflow posts from dec 2021, using discord.py
Help me
You’d be doing this anyway in any fork
Why do all those discord libraries look the same? 😳
Lol
Most of them are forks of discord.py
Well, that makes sense.
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
guild_id = 915076185740939304
# if they remove the reaction remove the role
if payload.guild_id == guild_id:
reaction_roles_data = self.reaction_roles_data[payload.guild_id]
for reaction_role in reaction_roles_data:
if reaction_role["emoji"] == str(payload.emoji):
role = discord.utils.get(payload.member.guild.roles, id=reaction_role["roleID"])
await payload.member.remove_roles(role)
break
error:
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\wolf\Trello\venv\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\wolf\Trello\cogs\Reaction.py", line 98, in on_raw_reaction_remove
role = discord.utils.get(payload.member.guild.roles, id=reaction_role["roleID"])
AttributeError: 'NoneType' object has no attribute 'guild'
Someone help
trying to get my bot to send new players a message but it wont work
@client.event
async def on_member_join(member):
await member.send("hello")```
```26.02 16:36:47 [Bot] Ignoring exception in on_member_join
26.02 16:36:47 [Bot] Traceback (most recent call last):
26.02 16:36:47 [Bot] File "/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
26.02 16:36:47 [Bot] await coro(*args, **kwargs)
26.02 16:36:47 [Bot] TypeError: on_member_join() missing 1 required positional argument: 'member'```
not really sure how to fix it
Can we see your entire file?
you are missing an arguement
!paste
the whole code?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
on_member_join(ctx, member)
Yes
nextcord or pycord ?
uhh how do i check
Don't make any requests in on_ready
2.
requests is blocking, considering using aiohttp instead
3.
Consider using cogs
i'll have a look thanks
Someone help pls
none
which u sue
!pypi disnake
- on ready fires multiple times
can someone help me with this
it keeps on saying enable tracemalloc
but im not sure where i need to add that
Don't use DiscordComponents
because i do not need to await anything
🗿
Send the traceback
line 167, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 40, in tictactoe
await ctx.send(embed=embed,view=view)
File "/home/runner/Tuition/venv/lib/python3.8/site-packages/discord/abc.py", line 1368, in send
raise InvalidArgument(f'view parameter must be View not {view.__class__!r}')
discord.errors.InvalidArgument: view parameter must be View not <class 'coroutine'>
The above exception was the direct cause of the following exception:
, line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: view parameter must be View not <class 'coroutine'>
/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'Command.__call__' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
done
👁️👁️
oh i just realised error i forgo to callback
tictactoe takes no arguements but ur passing in ctx
wdym
if message.embeds:
if "New Emote Appears" in message.embeds[0].title:
await message.channel.send('That Emote is HOT!')
I want it so my user bot sees other messages and not just its own how do i do that?
show more code
Would this code be the correct way to save something in sqlite
@leveling.command()
async def enable(self, ctx):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT leveling_is_active FROM levels WHERE guild_id = '{ctx.guild.id}'")
result = cursor.fetchone()
#1 == yes && 0 == no
if result == 1:
sql = ("UPDATE levels SET leveling_is_active = ? WHERE guild_id = ?")
val = (1, ctx.guild.id)
cursor.execute(sql, val)
db.commit
await ctx.reply("Leveling is already enabled.")
cursor.close()
db.close()
else:
sql = ("UPDATE levels SET leveling_is_active = ? WHERE guild_id = ?")
val = (1, ctx.guild.id)
cursor.execute(sql, val)
db.commit
await ctx.reply("Leveling has been enabled.")
cursor.close()
db.close()```
Because it keeps saying `None` when i print the value
the values goes after the " in the end of an sql statement
and again, you used placeholders in some parts but not in the first part
so something like this
await cursor.execute("UPDATE members SET user_id = ? WHERE guild_id = ?",ctx.author.id,ctx.guild.id)
it had an error, saying it requires 0 positional args but it were given 2
ok imma try that
oh yea so for sqlite, you have to add an extra comma after the last arg like this
before:
,ctx.author.id,ctx.guild.id)
after
,ctx.author.id,ctx.guild.id,)
how come?
idk its just like that for sqlite
Prolly so code knows difference
you dont have to do that in postgres tho
ok
still same error o-o
@bot.command()
async def alex(ctx, arg):
name, leng, amt = arg.split(':')
users = 0
name = name
leng = leng
amnt = amt
for i in range(int(amnt)):
user = "".join(sample(ascii_lowercase+digits, int(leng)))
users += 1
print(f"{user} | {users}")
buffer = BytesIO(user.encode('utf-8'))
discord.File(buffer,filename=name)
await ctx.send(file=file)
send the error and what is it supposed to do
can you show me ur code?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
It’s suppose to make txt files of strings depending on input
@leveling.command()
async def disable(self, ctx):
db = sqlite3.connect('main.sqlite')
cursor = db.cursor()
cursor.execute("UPDATE members SET user_id = ? WHERE guild_id = ?",ctx.author.id,ctx.guild.id,)
result = cursor.fetchone()
#1 == yes && 0 == no
if result == 0:
sql = ("UPDATE levelingenabled SET leveling_is_active = ? WHERE guild_id = ?")
val = (0, ctx.guild.id)
cursor.execute(sql, val)
db.commit()
await ctx.reply("Leveling is already disabled.")
cursor.close()
db.close()
else:
sql = ("UPDATE levelingenabled SET leveling_is_active = ? WHERE guild_id = ?")
val = (0, ctx.guild.id)
cursor.execute(sql, val)
db.commit()
await ctx.reply("Leveling has been disabled.")
cursor.close()
db.close()```
my guy
indent it
@bot.command()
async def alex(ctx, arg):
name, leng, amt = arg.split(':')
users = 0
name = name
leng = leng
amnt = amt
for i in range(int(amnt)):
user = "".join(sample(ascii_lowercase+digits, int(leng)))
users += 1
print(f"{user} | {users}")
buffer = BytesIO(user.encode('utf-8'))
discord.File(buffer,filename=name)
await ctx.send(file=file)```




lol, just to upload custom emojis
