#discord-bots
1 messages · Page 80 of 1
heres the on_ready part, it was at the bottom but moved it to the top, before the whole cogs part
Alright good, You should use discord.ext.commands.Bot.setup_hook and just load your cogs with discord.ext.commands.Bot.load_extension, a good way is to get the directory that contains all the files that contain a Cog subclass and iterate through each file and load the cog by the files name
I have a question, is it possible to send a message after a person has replied to a bot message through the "reply" item?
I advise you to watch the tutorial on how to simply launch a discord bot and display a message, and after that google those things that you are interested in doing (if you didn’t find anything, like in my case, then look for help)
in general, although I am far from an expert, my 1 hour was the same. Well, again, about my message, ask around, I'm a so-so teacher
I've been in this thread for a month and a half
overall a newbie
I think that you are trying to edit the variable mess which is an interaction, not a message.
where have you defined mess?
are you available to help me with it? i cant seem to understand how i can do that
hi anyone know how can i stop the error show cause its not an error
error handler 🗿
you were already answered
ye but idk how to add it in my code
bruh
why are you using ctx if it's an interaction, and you cannot edit interaction msg directly
because it is pycord and there is InteractionContext 🤢
or smth like that
so how i add it into my code
somehow
bruh
Its not weird, its terrible
i have added that
@bot.event
async def on_command_error(ctx, error):
pass
and the error stop show
message content intent
async def send_mute(user, reason: str):
channel = client.get_channel(925912014398844998) # channel mute case put in
em = discord.Embed(title="**MUTED**",
color=discord.Color.red())
em.add_field(name='Member:', value=f'{user}')
em.add_field(name='Duration:', value='1 day')
em.add_field(name='Reason:', value=f'{reason}')
em.set_footer(text=f'Provided by Donks#1048 • {current_time}')
em2 = discord.Embed(title="**MUTED**", description=f"You have been muted because: {reason}",
color=discord.Color.red())
await channel.send(embed=em)
await user.send(embed=em2)
@client.command()
@has_permissions(manage_channels=True)
async def mute(ctx, user: discord.Member):
date = timedelta(minutes=1440)
await user.timeout(date)```
Why isnt this muting user?
Hi
Hi so
the way i muted a member was with this
So do
await user.timeout(discord.utils.utcnow()+date)
make sure all intents are enabled for bot
Where wld i implement this?
async def button_callback_2(interaction):
await interaction.response.send_message(f'Disapproved and muted user!')
await send_mute(message.author, f'Suggesting non-needed post for #{channel_sent_in}')```
You would change this to the one i sent
So you know where you got the token for the bot
if you scroll below you see this
just tick intents
and it should work
otherwise im not sure
after enabling them
you know the area where you initialised the client
like client = discord.Client()
Put intents = discord.Intents.all() above it
and then change client to
client=discord.Client(intents=intents)
intents = discord.Intents.all()
client = discord.Client(intents=intents)
if it is still confusing
check out this post
https://stackoverflow.com/questions/70920148/pycord-message-content-is-empty
nice
i’m currently getting this error:
TypeError: TypedDict does not support instance and class checks
I found this report but i’m not sure how i fix the error: https://bugs.python.org/issue44919
guys how do i make my bot send command without prefix
Hello, I have been away from discord.py for a few months and when i came back, i noticed that my code isn't fully working like before i left
what's not working anymore is how i access my db
i use aiosqlite as my database, how i access it is like this
async def start():
await client.wait_until_ready()
client.db = await aiosqlite.connect("test.db")
@client.command()
async def test(ctx):
print(1)
async with client.db.execute("SELECT * FROM test") as cursor:
print(2)
tests = await cursor.fetchall()
print(3)
async def main():
async with client:
client.db = await aiosqlite.connect("test.db")
client.loop.create_task(start())
await client.start(TOKEN)
if __name__ == "__main__":
asyncio.run(main())
asyncio.run(client.db.close())
print(1) does print but it stops after that, meaning the command stops at async with part, so i am not sure why it happened since it used to work fine like 1-2 months ago
command_prefix=""?
thx
Working fine a few months ago doesn’t mean much
Discord.py has had some MASSIVE updates
Many of them breaking changes
yeah what i am asking is what am i missing from those updates lol
for it to stop it
You probably want to move your database connection into setup hook
hmm how so?
idk how to do this
i tried sqlite3 and the same thing happened
hey, i use my raspberry pi to host a discord bot,
i sometimes have issues with the Pi and want to use heroku as a backup sometimes
rn my main has 0 credits for the free working dyno
i made an alt on heroku but the bot wasnt running, so i also made an alt on github to connect to a diff account, still doesnt work
any suggestions?
why not subclass the client and make your own class?
hmm? will that fix my problem?
still offline tho
i have requirements file, procfile, and runtime file
It's better to figure out what's wrong with the Pi and fix the root of the issue
You can include a setup_hook if you subclass, yes
hmm is there any documents about it?
!d discord.setup_hook
No documentation found for the requested symbol.
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
oh thanks
if you want an example:
class MyBot(commands.Bot):
...
async def setup_hook() -> None:
# setup anything you need to here
bot = MyBot(...)
bot.run(...)
@split merlin
alrigjt thanks
is it okay if i have a command, when its used, the script calls a function that does the following:
-does webscraping (ab 11 pages or 22 pages)
-updates data in an sqlite3 database (ab 300 tuples or 600)
its gonna be a long pause, but idk how to make it do that whilst being able to respond to other commands
I suppose.. I haven't seen it used that way, so I'm not 100% sure. You should be using setuphook just to be sure
If it is blocking, you could use https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
Or look for asynchronous alternatives (like aiosqlite module for accessing sqlite databases)
ok thanks
What about that?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Yeah that's correct. But that wasn't op's problem. It was a function blocking the event loop
You're right but this isn't about defering it's about blocking the event loop
can i also have examples of sub classes? i didn't use them before so idk how to implement cogs and commands to it
For databases and discord bots usually a good idea to go with an asynchronous version. Aiosqlite and asqlite are popular
!resources I wouldn't be able to explain. Subclasses and inheritance are OOP topics and should be learned on your own
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
alright
I wonder which module allows for webscraping asynchronously
im stuck can someone help me understand what to do now?
this is my code: https://paste.pythondiscord.com/okidiyeral
and thats what i want to achieve:
For every user i want to create this row with
His number defined in embed above, values buttons about modes values ({"bedwars": True, "duels": True}), save button
On values button click i want to change value to negative from current one
On save button click i want to save current player mode values and save them back to database
i wrote all comments directly in code in that paste link
You know you can only have 5 rows of buttons right
So you can have only 4 users on there (1 row is the top row)
Yes the maximum amout of users will be 3
So there will be even 1 more spot
does anyone know how to get an actual member object from a ping? im saving it as "<@167826whatevernumbers>" But when I try to set permissions for that user it tells me it needs to be a role; or maybe a way to convert that to the member object?
you would use its id to fetch the member from that specific guild
The numer after @ is an id you can get member object you Can do await bot.get_user(id)
thats not a member object?
Or bot.fetch_user(id)
they both return a User object?
That's most likley the same
They're not the same.
so take out the <@ > and use the number in the get_user function?
Its a method and to be specific its name is a snowflake and it returns an instance of User , which you specified you wanted an instance of Member object, no?
okidoki, shall try
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
this is what you're looking for, no?
Maybe, if that returns it as a member then yeah thats what im looking for, got a lil lost with what Down said, but its alright, ill try this out in a moment
It can return Member | None
Hey i see you know how discord modules work very well do you mind looking into my problem?
sure
Its there
Its complicated i would say
The issue?
im explaining all in the code
i noticed im doing something wrong on line 52
there are comments everywhere almost so
anyone know how i can fix that
i have do the pip thing but i got
ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32)
ERROR: No matching distribution found for pywin32>=223
Just dont subclass discord.ui.Button its unnecessary and unneeded, just use the decorator discord.ui.button that registers the button to the View subclass it's inside in, so you can access all the values in any button
hm okay ill try doing that
nope now it all messes up and doesnt even add buttons in for loop
you can just statically add them
the amount of users is changing so it must be in a for loop
it can be 1 or it can be 3
ahh, so the saving button is also dynamic?
what do you mean by setting button
saving*
yeea
i want to add also Save all below
to save all changes
its gonna be hard to code i think
@slate swan upon thinking, why not just pass each config button instance to the save button?
how can i
does self.add_item return instance?
make a variable with the instance and add them to the view and then to the SaveButton
i think this is too many combining
im thinking with creating a class of User
and then creating it all inside it
It returns None
No, no, its quite easy
so i have access to it inside that class but how can i add that to View
why it must be so hard
anyone know how i can fix that
if its not discord-bots related i suggest creating a help channel
read #❓|how-to-get-help
but it is for a bot
for i, (uuid, user) in enumerate(users.items(), 1):
self.add_item(nextcord.ui.Button(label=i, style=nextcord.ButtonStyle.blurple, row=i)) # add numbers corresponding to a player defined in embed above View
for mode, value in user.items():
self.add_item(config:=ConfigButton(mode=mode, value=value, row=i)) # add switchable config buttons
self.add_item(SaveButton(label="Save", row=i, config)) # add save buttons
and then upon the callback of the save button just check the values of the passed button
maybe, but ModuleNotFoundError isnt especially discordbot related
alr i will tr in the help thing
alr give me few seconds im trying my solution with User class
Alright
pip install discord==1.7.3 iirc
whats iirc
k i give up
if i remember correctly or if i recall correctly
try my way!
yeah but i think i need to create list of buttons
cause now it would pass only last one or error
can you explain your issue?
its indented outwards
Pardon?
the SaveButton is not in the for loop adding ConfigButton
But its inside
for i, (uuid, user) in enumerate(users.items(), 1):
self.add_item(nextcord.ui.Button(label=i, style=nextcord.ButtonStyle.blurple, row=i))
?
what
Yeah youre saving the button inside of the parent for loop as i said?
!e ```py
for i in range(9):
print(i)
print(i)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 8
it will only add last element
its inside of the parent loop?
I'm so confused
How do i make commands non case sensitive? for example if i did /help it will pull up the menu but i also want it to work if they did /HeLp
all commands or just one?
all
slash commands already work like that...
theseare prefixed
slash commands does it automaticly
you can pass argument to bot
its for prefixed commands
Thats nice to know
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
case_insensitive=True in your commands.Bot instance
!d discord.ext.commands.Bot.case_insensitive
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
ah tyvm
yeah this
@primal token your solution works
😭
at least for now lol
I love how i'm confused but yet i helped you😭
lovely😭
hm i think im dumb... what am i doing wrong here then... figured that would be simple
i see that it says this.. Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well. but i set it in the group command as well
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('cogs.mod2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
It keeps returning none and I don't know why :c
So if i do this
helpcmd command is not case insensitive but the console and rcon are.. so i can do +helpcmd RcOn or +helpcmd CoNsOle and they work fine with that code but not the helpcmd itself... if i did +HeLpCmd.. or +hELpcMd RcOn
it happens when the user isnt in cache
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Changed in version 2.0: `member_id` parameter is now positional-only.
use this, only if Guild.get_member returns None so you dont need to do unneccesary calls ^
member = guild.get_member(float(newString.split(" ")[0]))
just to make sureee this is how its supposed to look right?
shouldnt use camelCase, it should look something like
member = guild.get_member(id) or guild.fetch_member(id)
ping when you reply please
gotcha, the split is just because im taking a message with 2 pings and I want to individually make them into a variable, but okay gotcha, ill check out the fetch_member thing
Nevermind I got it working..... had to change something i didnt even think about
i had to do this now everything works non case sensitive..
just posting in case anyone else runs into this problem
member = await guild.fetch_member(stringid.split(" ")[0])
this worked thank you 
wth does int ents mean it won't let me start my discord bot without it and i googled it and nothing good poped up
Change to the developer terms of service? What is changing?
load extension method is a coroutine, u need to await it
!d discord.Client.intents
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
@rancid inlet pls help
Please don't ping random helpers
Ok
Wait for someone to help here or open a help channel with the instructions at #❓|how-to-get-help
K
do u have a requirements.txt file?
Fixed
for pip i mentioned pep
Mis typed
hey could anyone please help in #help-popcorn
quite simple
i havent used python in a few weeks and now none of my code is running. It says the error is from "client = discord.Client()" and intents is mandatory or smth. when i type "client = discord.Client(intents = intents)" theres an error on the line in "client.run(token)". send help ty
intents = discord.Intents.default()
tysmm
@bot.command(name='vault')
async def vault(ctx):
await ctx.send("**__Enter password to continue...__**")
pswd_check = []
async def check(message):
print('checking if func working')
passwords = ['table']
for word in passwords:
if word in message.content: pswd_check.append(word)
break
await bot.wait_for('on_message', check=check)
how come the wait for check is never even called? it seems to still wait for it, as a print after the bot.wait_for isnt called
the reason i say it doesnt call the check, is because the print at the top of the check func never prints
The check cant be a coroutine and why even is it, its not even need?
yeah i think i just figured out that was part of my problem
ok i have one other issue; the bot.wait_for seems to be on a loop; i cant get to code beneath it
yeah i fixed that one
how do i break out of that loop
Replace break with return True
ahhh so the wait for is waiting for something to return true or false
that makes sense
since i wasnt returning a value it would of automatically returned false.
ah great, cheers!
you forgot to await it
Good resources hosting a discord bot in EC2?
What are you looking for? Just install python and run it as usual
i have
def check(message, user):
if user.bot is False:
for word in passwords:
if word == message.content:
pswd_check.append(word)
return True
await bot.wait_for('message', check=check)
why does this come up in the terminal;
TypeError: check() missing 1 required positional argument: 'user'
my checks have never needed arguments before
apart from message anyway
Remove user from check and use message.author instead
alright
why not just do if message.content in passwords:?
in this example here, how would i go about deleting the previous set of entries? ie keep the most recent 2, but delete the prior set to avoid spam
this isnt in a set channel, so i cant just delete all
i know how to delete the current set, but idk how id remove the ones above
i can do, but will that be an issue if im trying to have multiple "vaults"? where each one is seperate. I guess i could do ```py
if message.content in passwords:
x.append(message.content)
tho is content part of a msg...?
or the whole
What do you mean by trying to have multiple "vaults"? where each one is seperate
simply that depending on what pswd is entered, it opens a different door so to speak.
like so;
if pswd_check.count('exit'):
await ctx.channel.send('*Closing Vault...*')
return
if pswd_check[0] in ['table', 'chair']:
it really comes down to this
i can manage my seperate rooms
if content means the entire msg, i can then just append the message in the way that noid was suggesting
how can I get disk usage , memory usage and cpu usage by the bot and send it?
What is if pswd_check.count("exit") for? Why not simply use if "exit" in pswd_check?
!pypi psutil
yeah since its just a single str, thatd work just as well
You either need to delete them after some time or create some kind of list with Message objects and if its length reaches 3 for example delete the first message
oh ye
how would i get the message objects ?
You get them from wait_for
Your mistake here is that you operate with message object in check, that's incorrect method. You should just do this
message = await bot.wait_for("message", check=lambda m: m.author == ctx.author)
And then just operate with message
How to add buttons in discord bot?
Can anyone send the docs for buttons in discordpy?
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
It's better to look at the examples on their repository https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
""""Hack Command"""
@commands.slash_command(name="hack", description="Hate someone? Hack their account!")
async def HackUser(self, inter, target: disnake.Member):
Embed1 = disnake.Embed(title="",
description=f":Load: Hacking {target.display_name}...",
colour=disnake.Colour(0x2f3136))
Embed23 = disnake.Embed(title="",
description=f":Load: Injecting malware: Trojan, Viruses, Worms, Ransomware...",
colour=disnake.Colour(0x2f3136))
Message = await inter.channel.send(embed=Embed1)
await asyncio.sleep(3)
await Message.edit(embed=Embed23)
await asyncio.sleep(3)
This sends and edits the msgs but for some reason, when I do the interaction, it sends this.
What do u guys think is the problem?
You aren't responding to the interaction
Wym?
Pro naming convention
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
You have to respond or the interaction fails
You need to call some Interaction.response.x to respond
ahh, alright
Wait. Lemme try
And respond within 3 seconds
how would i go about pulling a user ping from a message, and using that in a diff func?
so for example if someone else pinged me;
@jagged adder like so; is there a way to pull the id of the person that was pinged (not the message author) and then use that id for something? ie so the bot can say
"pst @jagged adder, someone wants you"
as an example
@vocal snow u seem to know your shit when it comes to this kind of thing; got any ideas?
on_message event and use message.mentions
wydm by message.mentions?
message.mentions returns a list of members that were pinged
Note I am not actually a genius...
ah
Still don't get it? Mhm ahhh
where do i put the message.mentions tho
You are using a on_message thingy right?
im using a bot listener atm
but pretty much yes
@bot.listen('on_message')
async def ping(ctx):
if ctx.author.id in [..., ...]:
l = ctx.mentions
print(l)
otherwise it breaks my commands
made an edit, and now i see the list u were talkin about
mentionedperson = message.mentions[0] is how I would do it
yeah i was just testing with the above
Oh this should work I think
kk nice
yep u got it
now to mention them using the id...
Very easy
@shrewd apex
nice
now the only thing left is sending an automatic msg to my sister at a set time tmrw; everything else has been designed and finished! (for context, i am creating a little bday surprise within my bot for her bday)
sorry if this counts as spam :p
id like to thank the various peeps who have helped me out over the last couple days in getting this together and working; cheers yall!
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.
👍
You can set the button's callback function
view = View()
button = Button(label="Ping")
view.add_item(button)
async def button_callback(interaction: discord.Interaction):
await interaction.response.send_message("Pong!")
button.callback = button_callback
But it's better to just subclass the view.
does anyone have a src for a Premium system for .redeem and .gen
where do i put this? intents = discord.Intents.default()
what line
figured out tyyyyyyyyyyy
Inside your bot or client constructor
THANKSSSSSSS
i have another issue
By putting inside your bot or client constructor I mean
client = discord.Client(intents=discord.Intents.default())
how to send message in discord,py with out ctx ot message attribute?
Fetching channel and use channel.send
i changed it ty now i get : 'function' object has no attribute 'run' -_-
okay
Can you show your full code?
wait no actually how to send message in a interaction
I have a interaction in a class
ill just reset it
I am faster than u kid
but no worries I will not do anything
already did lol
!d discord.Interaction.respond
That's sad
I wanna send a message after the interaction responce
alright so what do i do?
You can use interaction.followup
WORKEDDDD
you are a beginner right?
Is there a way to disable this? Sends twice because I'm hosting the bot using this hosting site
What's the hosting site
yea
GOOD LUCK! on your Learning Journey 👍
thank you 😄
It's not a well known site (Still also a bit skeptical about it) But it's called daki.cc
imma continue making my bot thanks for help , cya!
Can't really host with Railway rn since my GitHub acct's too new
for my opinion Github is not the great place to host bots
Are you sure you didn't accidentally send the embed twice
Well then I can't help with that
Here's the code for conifrmation:
Random = ["Heads!", "Tails!"]
Randomize = f"{random.choice(Random)}"
EmbedFlip = disnake.Embed(title="",
description="*The coin is flipping...*",
colour=disnake.Colour.random())
EmbedResult = disnake.Embed(title="",
description=f"**__{Randomize}__**",
colour=disnake.Colour.random())
Message = await ctx.send(embed=EmbedFlip)
await asyncio.sleep(3)
await Message.edit(embed=EmbedResult)
Ouch. Welp. I guess I'll have to look for google answers lol
Also noticed that it only sends twice for prefix cmds lol.
I am getting this error
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
await item.callback(interaction)
File "c:\Users\8ster\Bot\main.py", line 80, in variable
await interaction.followup("HEY")
TypeError: 'Webhook' object is not callable
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
OK I think I need to use this
Since the interaction.followup is a webhook object, you have to use that
error T-T
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
await item.callback(interaction)
File "c:\Users\8ster\OneDrive\Desktop\projects\Discord Bots\Mighty Raju Bot\main.py", line 82, in rock
await discord.Webhook.send("I LOST :-(")
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1673, in send
if self.token is None:
AttributeError: 'str' object has no attribute 'token'```
why do I need token here
I mean
bruh
Use interaction.followup.send
I swear nobody starts discord bots after learning OOP lmao
I high school students doesn't have lot of time
we have to do a lot in a limited day BRUH
how is that an excuse for not learning relevant knowledge to what u are attempting to do
well yes
i tried to start leraning it for 4 days
I GAVE UP
Bruh lol. At least learn and try kek
now I just seek to through documentation and write code
Anyways. Question:
What does sync_commands do?
they are not async simple?
I need references
They're not.
like the sync with the program commands
have time to make bots, alright
which library is this
Disnake
Can't really write code rn since I'm at phone so for now, I'll just ask what it does
it's just a setter if disnake should automatically sync the slash commands with the discord api for you or not
bot = commands.Bot(...)
bot.sync_commands = False
that's how you use it
Alright. Noted
it's defaulted to True too
yes though there's an issue that even if no changes were made to your commands and you run the code, it'll sync the commands again and you'll eventually hit ratelimits
ok fine atleast u read docs situation can still be salvaged 
Alright. Will keep this in mind. For now, gtg. Thsnks gor the help
#help-bread if you have time to look into it
no someone who understands discord bots well
no just asking there cause my channel is based on discord bots ...
Is this discord.py?
Hey @dim geyser! 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!
import os
from neuralintents import GenericAssistant
chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_mode()
print("Client running...")
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startwith("$aibot"):
response = chatbot.request(messge.content[7:])
await message.channel.send(response)
client.run(#token)
i keep getting no model named discord
help please
Ah, well, first thing is you should use bot.event instead of bot.listen; second, there's no such event as on_button_callback.
hmm why not listen?
u have to add callback for button
no not an event
wait lemme check pycord docs
can someone help me now?
import os
from neuralintents import GenericAssistant
chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_mode()
print("Client running...")
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startwith("$aibot"):
response = chatbot.request(messge.content[7:])
await message.channel.send(response)
client.run(#token)
i get no model called discord

same as dpy callback
How do you run the script and where are the modules installed
i went to my command prompt and typed pip install discord.py
well pycord discord disnake nextcord 99% of the time similar syntax
and pip install neuralintents
What code editor do you use
You can use on_interaction and check the interaction type if it's from a component
Might be, pycharm necessarily uses venv
And you might mess it up if you don't know how it works decently well
Asher 😭 why isn't vsc determining the return types
nope u still have few stuff u did wrong
what editor should i use?
Pycharm is okay
then how do i fix it
sed life 
just use pycharm
@dim geyser what message do you get after pip install
just pip install?
I deliberately hate it
i always find vsc linter for python too slow
ERROR: You must give at least one requirement to install (see "pip help install")
use sublime text then 🙏
that's a good option too, I even have it installed
use neovim 😎
assign callback to button and its not ctx its an interaction object
I need the message you get after installing literally any package
and its interaction.data["custom_id"]
@dim geyser
help me fix it??
see code:
bad_words = ['hii', 'world', 'never']
@client.event
async def on_message(message):
await client.process_commands(message)
for bad_word in bad_words:
if bad_word in message.content.lower().split(" "):
await message.delete()
bad_word_embed = discord.Embed(title = "Bad Word", description=f"{message.author.mention}, please do not say any bad words")
await message.channel.send(embed=bad_word_embed, delete_after=5.0)
How is client defined
client = discord.Client uwu
what?
Imagine if uwu was a keyword
this automod is bad word and auto delete
just use discord's automod-
just use discord inbuilt automod 
yes
package main
import "fmt"
func main() {
var bruh uwu
fmt.Scan(&bruh)
fmt.Println(bruh)
}```
Just use my bot it's cool (no ads btw)
🤢
this look like failed fusion between cpp and python
That is go!
give show code
Add it
where ur eols ;-;
Link in bio
evenfix bio flex 
Cuz you won't understand its code I am 69% sure
i am 96%
What's eols
bruh! show me code!! is good work
end of line
Check my github!
ok
epic promotion time
which title??
Just star them all 😉
AIAS
hey 9047064c7ec960627a11743bfa49b0af3e8dd702ef771cec3e908b5cd28b477e
@vale wing can help me??
code:
class myclient(discord.Client):
def __init__(self,*, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=all)
await self.tree.sync(guild=all)
how all server in my bot?
no offense but this is what happens when u start of with no basics u stumble at every step
u changed the param to Interaction but in ur function u left it as ctx
so u will get ctx undefined error
button = discord.ui.Button()
button.callback = callback
Change the button.callback by doing something like
button = discord.ui.Button(...)
button.callback = callback # your callback function
view.add_item(button)
What can I tell ya
Your button at line 123 is unused
And your button at line 137 has no callback function
this dude exenifix always in here man
You need to assign the callback to it for it to work, but you're just creating a button and instantly adding it to the view without the callback
^
its jus this one dude thats an expert essentially at dpy and hes always helping in here for months lol
Hey @dim geyser!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
https://paste.pythondiscord.com/gayahihecu i keep getting this error
can someone help?
show code
import os
from neuralintents import GenericAssistant
chatbot = GenericAssistant('intents.json')
chatbot.train_model()
chatbot.save_model()
client = nextcord.Client()
@client.event
async def on_message(message):
msg = message.author
if msg == client.user:
return
if message.content.startswith("bot"):
response = chatbot.request(message.content[2:])
await message.channel.send(response)
client.run("#token")```
wht is this trying to do?
a chatbot
everything is fine until i get that error
for some reason
it tells me to install ntlk and i have absolutely no idea what that is
what do you mean
uhhh idk man
its with chatbot.train_mode()
nltk, not ntlk as the screenshot above says
oh
I think it's missing a dataset and asking you to download it
but how, i literally started coding like a week ago
now ```py
import nltk
nltk.download("omw-1.4")
i should do that on the terminal?
i would also recc joining the nextcord discord too because its always very helpful in help channels
It's telling you in the error message 
if you wanna use the terminal, type python which opens python in the terminal
then write these lines
else you can write it in a py file and run it
What's the error in console?

They didn't add a callback kek
There's no event named button_callback
I'm gonna keep the screenshot of that
You just need to assign a callback to the button
I've explained it to you before
If that's not what you wanted, then you have to use on_interaction and check if the interaction was from a button.
moment when thinking is our super power
Check if the interaction.type is component
Like
if interaction.type.value != 3:
return
Return if the type of interaction is not component
Idk if the on_interaction will affect your slash commands or not if you have one
!d disnake.on_button_click
disnake.on_button_click(interaction)```
Called when a button is clicked.
New in version 2.0.
Ok only disnake has this
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
Disnaek gud lib 🥵
🫠
🫡
disnake 💀
well if u want an event so bad u can dispatch ur own custom event
but i don't see how having a button press event is more useful than interacting in callback
the best fork of d.py
but then also me at the same moment 💀
How would i go about setting up an event or task that will go off at a set time? ie 12pm on x date, either using epoch or some such
https://paste.pythondiscord.com/hapijitoqa <— is my current snipe command code. My main error is when I delete any message in "server one" and then use the snipe command in "server two", the deleted message from server one displays in the response from snipe in server two. How can I limit this so it only shows deleted messages from the guild the snipe command is executed in? Also, can I optimise this code in any way? I feel like it’s quite unnecessarily long.
That's a bunch of global variables
You could use dictionary for that
where can I learn about dictionaries?
!dict
» iterate-dict
» dictcomps
» dict-get
Well, Google and Stackoverflow are your friend
But basically it's key-value database
Didn't me and someone tell that a few days ago
database? isn't it a data type huh
ello
That's what they told me
it's not a database
Maybe because I'm just bad at python
and yes, somewhat; im having issues filling in the gaps online tho, so i was seeing if anyone else had an idea
what are the issues you're facing
I'll give you an example
from discord.ext import tasks
from datetime import datetime
@tasks.loop(time=datetime.fromtimestamp(123456789)) #epoch value
async def my_task() -> None:
...
my_task.start()
easy as that
so does the my_task.start() begin the loop process?
and keeps running it indefinitely
time=datetime.fromtimestamp(123456789)
``` is defined as an unexpected argument tho
Use datetime.time instead
@loop(time=datetime.time(minute=30))
...
this is for the loop part; how do i check for when it hits x time tho
ill prob need to have an if in there
Set count for it
@loop(count=10, ...)
ie if datetime.now() == x
Ah, I misunderstood that
i can have it loop, but it needs to check if it equals the correct time at the point it loops
otherwise its kinda useless
yes, it won't
at least because Role can't be created like this
Role(id) is not a thing
also it's interaction.user
not interaction.author
no
!d nextcord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
no bruh
no bruh
first of all interaction.user
second it's not nextcord.get_role(id)
it's guild_object.get_role(id)
interaction.guild can be a guild object for example
🗿 you must be joking
bruh, idk how to explain that so you would understand
do you even know what are instances?
no?
So let's make an example:
class Apple:
def __init__(self, *very_important_params) -> None:
self.appleness: int = 100
self.info = very_important_params
def eat(*, full: bool = False):
...
``` This an `Apple` class right? Not an instance.
And now let's make an instance of this class:
```py
fresh_apple = Apple("very important param")``` So now, `fresh_apple` will be an instance of `Apple` class.
And so we can use it as we want with knowing that it has attrs and methods like `Apple` class, for example we can do `fresh_apple.eat(full=True)`
Here is an article about that: <https://towardsdatascience.com/practical-python-class-vs-instance-variables-431fd16430d>
@slate swan
how do i make it so it reads my token saved in another txt file?
why txt file 💀
config.py>>>>
.env>>>>>>>
It doesn't matter how, just wanna make my text safe ☠️
@polar scroll
Ok, how exactly
Here is an article on how to use .env in python @polar scroll
https://dev.to/jakewitcher/using-env-files-for-environment-variables-in-python-applications-55a1
ok, now i need to know about slash commands, i have been looking at learning them for a whole week, but i cant seem to undestand
Which library?
discord-slash-command
What is that 😳
its... a library..
that was created to help with slash commands
its not official ofc
Why not use a normal lib? Like discord.py, hikari, disnake, e.t.c
Then why do you need discord-slash-command?
following with that state, i cant seem to make slash commands, neither undestand the codes on yt tutorial
discord.py has slash commands implemented
-slash-command was for when discordpy wasn’t supporting
Neither that discord-slash-command nor yt tutorials are good
alright, so in .py... how do i make slash commands?
second pin in this channel
alr
Full code of this button's callback please
And I think code-blocks are better than ss here
!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.
await cursor.execute("INSERT INTO starboard (guild, channel) VALUES ($1, $2)",(context.guild.id,channel.id,))
sqlite3.IntegrityError: NOT NULL constraint failed: starboard.starLimit```
Most likely
It should give an error tho, if there is no ctx
am getting this error
CREATE TABLE IF NOT EXISTS `starboard`( `guild` INT(11) NOT NULL, `channel` INT(20) NOT NULL, `starLimit` INT(20) NOT NULL );
@checks.not_blacklisted()
async def set(self, context: Context, channel: discord.TextChannel) -> None:
"""
Set the starboard channel.
:param context: The hybrid command context.
:param channel: The channel to set as the starboard channel.
"""
connection = sqlite3.connect("database/database.db")
cursor = connection.cursor()
await cursor.execute("INSERT INTO starboard (guild, channel) VALUES ($1, $2)",(context.guild.id,channel.id,))
cursor.commit()
await context.send(f"Starboard channel set to {channel.mention}.")```
You are using pycord right?
Then I'm not sure what should you replace it to, search in docs what is a method to respond with an Interaction
that won't work most likely xD
Looks like context.guild.id or channel.id is None somehow, have you tried printing them? If yes, then what does it say?
im getting a small error when doing
from dotenv import load_dotenv
load_dotenv()```
it highlights the word "dotenv" in "from dotenv" as an error, do i need to download it? also, how am i supposed to get my token in my .env file?
i want to make my bot give the users have x on their inv
{
"875620201142562837": {
"inv": {
"blabla": 5
},
"has_x": true
},
"871068768254722129": {
"inv": {
"blabla": 5
},
"has_x": false
}
}```
thats what values looks like
Which error does it say?
how can i make my bot add 1 to blabla every user who has x every hour
import dotenv could not be resolved
what do you want me to print??
sqlite3.IntegrityError: NOT NULL constraint failed: starboard.starLimi```
CREATE TABLE IF NOT EXISTS `starboard`( `guild_id` INT(11) NOT NULL, `channel_id` INT(20) NOT NULL, `starLimit` INT(20) NOT NULL );
@starboard.command()
@checks.not_blacklisted()
async def set(self, context: Context, channel: discord.TextChannel) -> None:
"""
Set the starboard channel.
:param context: The hybrid command context.
:param channel: The channel to set as the starboard channel.
"""
print(channel)
print(context.guild.id)
db_manager.set_starboard_channel(context.guild.id, channel.id)
embed = discord.Embed(
title="Starboard Channel Set",
description=f"The starboard channel has been set to {channel.mention}",
color=0x9C84EF
)
await context.send(embed=embed)```
set a starboard channel
it will store the channel and server id in the database
How can I make it so that only the user who invoked the command can interact with the buttons
Perhaps it gave you a error bcs you are making query without giving starLimit a value @ionic edge
And you specified that the value can't be null
whats a cog?
cogs are a pretty decent way to organize your bot's commands and stuff. cogs are subclasses of the commands.Cog class in the commands extension and are usually placed in separate files and loaded as extensions.
better explanation > https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
Any idea?
help?
File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1055, in on_connect
await self.sync_commands()
File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 657, in sync_commands
app_cmds = await self.register_commands(
File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 485, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(self._bot.user.id, guild_id)
File "C:\Users\kakig\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
application.commands scope
Why do you have two bots defined in your file?
No
Remove the client variable
Whole traceback please
The whole error
It's known as a traceback, since it can trace back to the line which caused the error
!tracebacl
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Cool
async def on_member_join(member):```
how do i make this for specific server?
which database ??
like ttgus only
i need to enable it?
i mean its alredy enabled
async def on_member_join(member):```
how do i make this for specific server? discord.py
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 499, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 848, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\modules\mod\cog.py", line 196, in timeout
if time < timedelta(days=28):
TypeError: '<' not supported between instances of 'datetime.datetime' and 'datetime.timedelta'```
time is a datetime obj, you can't compare a datetime and a timedelta object
Just check if member.guild is a specific server in this event
Of course it is not printed, this callback is not attached to any button.
Seems like you removed button.callback = button_callback for some reason
It's the best docs out there imo
What is hard in reading them
You just need to know basic OOP
What 
Oh yeah, you are trying to attach the callback before it is defined, you need to put that after your async def button_callback(...): func
What's wrong?
if member.guild.id == my_guild_id: do stuff
@slate swan
if member.guild.id == my_guild_id(idhere):
is it like this?
It explains quite clearly in the parameters section
no?
then how/
just replace my_guild_id with your ID
Where do you think my_guild_id would be defined if you are trying to use it as a method bruh
What? I literally can't explain in any more depth than the perfectly constructed explanation already does
That is definitely not how it works
async def on_member_join(member):
if member.guild.id == my_guild_id:```
like this?
That was not a response to you
yes?
and how do i let it automatically find guild id?
If you're too stupid to read the docs then you won't understand me either to be honest. The docs are very clear
You have two options, time-out for x or timeout until x
If you want for x, then use a timedelta
If you want until x, provide a datetime
What do you mean by "find guild id"?
I've just explained your two options
nvm was trying to make the bot customizable
but i dont think its possible, with both bot command and bot event...
why not?
i dont think i can combine bot event with bot command 😦
Just save what you want in DB or JSON and get that in an event
the problem is i cant get databases to work and i arent familiar with JSON
What is the problem with DBs?
they. dont . work
You get an error? Burn out? Don't work doesn't say a lot to me
how do we get all the members in a guild?
all the member ids in a guild? using api requests?
!d discord.Guild.members pretty obvious
property members```
A list of members that belong to this guild.
oh, using api requests
yes
!d discord.Guild.fetch_members
hey
async for ... in fetch_members(*, limit=1000, after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s members. In order to use this, [`Intents.members()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") must be enabled.
Note
This method is an API call. For general usage, consider [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members "discord.Guild.members") instead.
New in version 1.3.
All parameters are optional.
Api request with discord.py or with ur own lib or something else?
Ah lemme pull-up the docs
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
imma see that thanks
yk what my question is, how do user accounts get something which required privileged intents?
like when you scroll down on the right side here, it shows all the users,
but isnt it a privileged intent?
Ur using a user bot?
what is a user bot?
selfbots ig
selfbot?
Same thing
thats impossible tho, when you put your token in the commands.Bot thing it says invalid token,,, i tried
😳
wtf 😳
Yeah it’s now unsupported
That uses a gateway operation
oh i see
Gateway, like connect with a web socket to receive events and stuff
Well that’s not a great explanation
I'm pretty sure the member list to the side of your client in the UX is a separate API used by actual users.
Sort of like how users have a search bar that uses it's own API vs a bot's search API (less powerful)
may be
I’ve seen a self bot library use it before
library? selfbot what are you talking about
You should be able to pull up the dev console on electron with a few tweaks to the files, and see the inbound and outbound requests to confirm that
I know the opcode for the get member sidebar list thing
nothing here showing where the user data is actually coming from, right?
But I’m just not gonna say it cause the rules here
Opcode 1 is heartbeat payload
someone unironically called the ws heartbeats ping pong lol
PING is an acryonym
tbf it's a good description
bytes bytes bytes, why is discord ws sending me like 10 packets every second?
what even is this shit 🤔🤔🤔🤔
Just did a quick search, so this might be the member list to the side
anyone know a good place to get examples from? (for example: moderation commands)
open source bot gists
like RDanny
I looked through all the client's OP codes via data-mine
I don't see it at all, mostly because that event is a DISPATCH Opcode
I'm assuming it's a dispatch at least cause I see emitters for it
Opcode 14 is something else
Checkout the unofficial discord api docs
I'm not reading the unoffical API docs I'm reading the data-mine
This was the one from the last 14 hours I think so this is pretty recent
Send me the link for the one pertaining the member list? I don't know how to nav
Why not send it here?
I'm not sure how I'm selfbotting?
can i make a cmd which bans a user and doesnt gets affected by the user changing there VPN..
Yea the unofficial docs here reference GUILD_MEMBER_LIST_UPDATE Which would make it an Opcode 0 then right? Because this is a t field
I didn't see any e.GUILD_MEMBER_LIST_UPDATE = 14 or whatever
Well I think you request the members then it sends them through an event or something
send code
I have a regular function that is called when i press 'p' on my keyboard, how do i make it so that my discord bot sends a message whenever I call that function. Im struggling because the .send() function has to be awaited and in an async function, but I cant call an async function when inside a normal function, asyncio.run() also doesnt work, throws an error
Ahh I see I was confused with e[e.GUILD_SUBSCRIPTIONS = 14] = "GUILD_SUBSCRIPTIONS"; but the unofficial docs reference subscriptions which makes sense now
I was thinking subscriptions in the sense of guild premium features
So that cleared up the confusion
Type:
Timeout command
Code:
intents = discord.Intents.all()
bot.session = aiohttp.ClientSession()
async def timeout_user(*, user_id: int, guild_id: int, until):
headers = {"Authorization": f"Bot {bot.http.token}"}
url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
json = {'communication_disabled_until': timeout}
async with bot.session.patch(url, json=json, headers=headers) as session:
if session.status in range(200, 299):
return True
return False
@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
if handshake:
return await ctx.send(f"Successfully timed out user for {until} minutes.")
await ctx.send("Something went wrong")```
**Error:**
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Timeout context manager should be used inside a task
```
?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
ok
you know what is wrong ?
warnings.filterwarnings("ignore", category=DeprecationWarning)
intents = discord.Intents.all()
bot.session = aiohttp.ClientSession()
async def timeout_user(*, user_id: int, guild_id: int, until):
headers = {"Authorization": f"Bot {bot.http.token}"}
url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
json = {'communication_disabled_until': timeout}
async with bot.session.patch(url, json=json, headers=headers) as session:
if session.status in range(200, 299):
return True
return False
@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
if handshake:
return await ctx.send(f"Successfully timed out user for {until} minutes.")
await ctx.send("Something went wrong")
At face value this seems to work, but consider that create_task will schedule the task of start coroutine which does API connections etc, but it's still concurrent and non-blocking. Meaning get_channel is called before the bot's cache is populated
why do you need to make web requests, isnt timeout supported in discord.py?
idk i found this on internet
very true
wait_until_ready would be an option I guess
import asyncio as aio
import keyboard
bot = Bot()
async def main():
aio.create_task(bot.start())
await bot.wait_until_ready()
channel = bot.get_channel(ID HERE)
while True:
if keyboard.getch() == "p":
# or something idk
await channel.send("hello")
aio.run(main())
this is just an example code tho
interaction.user
interaction.user, not author, I told you about that.
What 
anyone knows a timeout command ?
how to create an embed .-.
import aiohttp
import discord
import datetime
import warnings
from discord.ext import commands
warnings.filterwarnings("ignore", category=DeprecationWarning)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=['$',], intents=intents)
bot.session = aiohttp.ClientSession()
@bot.event
async def on_ready():
print(f"{bot.user.name} is ready to go!")
async def timeout_user(*, user_id: int, guild_id: int, until):
headers = {"Authorization": f"Bot {bot.http.token}"}
url = f"https://discord.com/api/v9/guilds/{guild_id}/members/{user_id}"
timeout = (datetime.datetime.utcnow() + datetime.timedelta(minutes=until)).isoformat()
json = {'communication_disabled_until': timeout}
async with bot.session.patch(url, json=json, headers=headers) as session:
if session.status in range(200, 299):
return True
return False
@bot.command()
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
if handshake:
return await ctx.send(f"Successfully timed out user for {until} minutes.")
await ctx.send("Something went wrong")
bot.run("BOT TOKEN")
Which library?
well actually they are similar
?tag embed
This is not a Modmail thread.
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
em = discord.Embed(title="hello")
ah yes that
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
HI all, I'm trying to lock my reaction role embed down to messages the bot posts to (without the message id) but struggling on how to do this. I am not running into any errors, tracebacks so if anyone could advise be much appreciated 🙂
https://paste.pythondiscord.com/unahedixur code for the on raw reaction add event here.
asyncio.run() cannot be called from a running event loop aio.create_task(bot.start()) (I rewrote as aio.create_task(bot.run(Token)) )
i really hate this because discord likes doing events in response to other events, but when I want to send a message to a channel basically randomly (whenever i press a button), I have to go around a pile of obstacles
I wish i could have done this in js lol. however im stuck with python because i rely on it to do other things
I don't really understand what you want, and in your code py if payload.message_id: return will trigger literally every time, so the bot will just ignore the reaction adding every time
doesnt work
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Timeout context manager should be used inside a task
huh
its from stackoverflow
why not just give moderators timeout permission lol
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 53.58 seconds
i haven't loaded up my bot in ages, it has 10 shards, why would i be receiving a rate-limit?
How could i fix it, i am using AutoShardedBot? I havent ran the bot in almost a week
Discord's way of welcoming your bot back 😄
for example when people react to a random post with 👍 this emoji is set in my dict for reactions role, currently anyone reacting to any message wiht that emoji will add/remove the role specified in my code, i am trying to make it so its only the posted embed created for reaction roles where they can add/remove roles..
how do i stop the ratelimit
are you doing too many await calls?
i dumbed it down to ust starting up
i have one await call which is running the tkn
import asyncio
import logging
import discord
from discord.ext import commands
class bot(commands.AutoShardedBot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned,
intents=discord.Intents(
guilds=True,
members=True,
messages=True
),
help_command=None)
async def startup():
logging.info(f'Starting Up...')
logging.info(f"Connected To {bot.user} with {len(bot.guilds)} servers")
pass
bot = bot()
async def main():
async with bot:
bot.loop.create_task(startup())
await bot.start('xxx', reconnect=True)
asyncio.run(main())```
do you see an issue here?
that is all yr bot.......?
Tf for you need create_task in an async func, I'd just await it
You access bot.user and bot.guilds using a task that was scheduled before bot.start finished caching
So bot.user is None and bot.guilds will be an empty list
Ah, good catch with that
oh, thank you
That too
But that shouldn't be the cause of ratelimiting?
yea..
Oh I didn't see your above message about ratelimiting
Probably the lib is tryna cache too many guilds all of a sudden?
Put it to on_ready cause why not
no
That happened with my bot and I had to disable the caching
im not using on_ready, thats terrible with dpy 2.0
Can you show the ratelimit error?
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 54.05 seconds
WARNING:discord.gateway:WebSocket in shard ID 1 is ratelimited, waiting 49.15 seconds
WARNING:discord.gateway:WebSocket in shard ID 2 is ratelimited, waiting 48.28 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 46.46 seconds
WARNING:discord.gateway:WebSocket in shard ID 4 is ratelimited, waiting 48.83 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 49.14 seconds
WARNING:discord.gateway:WebSocket in shard ID 6 is ratelimited, waiting 48.92 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 46.61 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 48.04 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 48.24 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 48.67 seconds
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 1 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 11 is ratelimited, waiting 48.34 seconds
WARNING:discord.gateway:WebSocket in shard ID 2 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 12 is ratelimited, waiting 49.10 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 0.00 seconds
WARNING:discord.gateway:WebSocket in shard ID 3 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 13 is ratelimited, waiting 48.39 seconds
WARNING:discord.gateway:WebSocket in shard ID 4 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 5 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 6 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 7 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 8 is ratelimited, waiting 59.98 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 9 is ratelimited, waiting 59.99 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 0.01 seconds
WARNING:discord.gateway:WebSocket in shard ID 10 is ratelimited, waiting 59.98 seconds
this is all it sends
Gg
How many guilds is this in?
like 7k
Are there like heavy loading loops
Okay it's fine to ignore it unless you are being disconnected. The wrapper is handling the ratelimits fine. Your getting these messages because discord.py does a GUILD_MEMBERS_CHUNK request everytime the bot is started up to populate member caches
You could pass an option to NOT CHUNK on startup which LOWERS your startup times but you will need to do custom chunking
Which is what I used to do
hmmmm
This means no caching unless you chunk though so unless you know what your doing, don't do it
yea
I've written an example of that somewhere in this channel let me find it
bot = Bot(chunk_guilds_at_startup=False)
chunked: dict[int, tuple[discord.Guild, datetime.datetime]] = {}
@bot.event
async def on_message(message: discord.Message) -> None:
if message.guild.chunked is False or message.guild.id not in chunked:
chunked[message.guild.id] = message.guild, datetime.datetime.utcnow()
await message.guild.chunk()
@tasks.loop(seconds=...)
async def check() -> None:
for id, (guild, time) in chunked.items():
if (datetime.datetime.utcnow() - time).seconds > 100:
del chunked[id]
i want to make a command for it
ok, thank you
But honestly I wouldn't use that at all, not unless your start up times are way to long
Or if your being disconnected which you shouldn't be
why.....
i've been getting the same error for days when a user interacts with a button. i've uninstalled py-cord and reinstalled it and removed any of the discord packages:
TypeError: TypedDict does not support instance and class checks
what's the full error?
!sql injection
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
you have an extra pair of parentheses after send_message
How can I make a task loop so it sends a message every x amount of seconds
is it possible to check exactly when a user left the server?
I forgot how to check if the bot has permissions
use if instead of elif
you use elif in case you already have an if
if a == b:
print('something')
elif a == c:
print('something else')
else:
print('idk')
@slate swan
Sure. Save the user leave time in on_member_leave
I don't know if it's that or on_member_remove
!d discord.on_member_remove
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") leaves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
If the guild or member could not be found in the internal cache this event will not be called, you may use [`on_raw_member_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_member_remove "discord.on_raw_member_remove") instead.
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
you're right
Anyone here know how to make classes/button with nextcord because i made so it send a embed after you click on a button and now i want to make a button in that embed that goes to another embed. Hard to explain
alright, thank you!
