#discord-bots
1 messages · Page 177 of 1
that's not your issue
your issue is that the bot is not registering your command
have you first of all verified that the cog is loaded?
you should surely add that on top of on_message as a decorator though, to state that it's an event~listener
https://paste.pythondiscord.com/juxivuyadi
Can someone show me how I fix that I can use more commands besides !hello
you haven't stated the problem
you haven't shown your main file either
Only the !hello command works
in your case, just do the first of what this links suggestes instead of the second
#discord-bots message
line 21 till 24 don't make much sense tbh

So this bit?:
@bot.event
async def on_message(message):
# do some extra stuff here
await bot.process_commands(message)
your issue is in line 21 till 24
just make a repeat command like
if you want to repeat what a user said, read this
https://discordpy.readthedocs.io/en/stable/faq.html#why-do-my-arguments-require-quotes
notice that on_message even there?
#discord-bots message
also process commands goes after your on_message stuff also use a setup hook for db
you have to add that process command shit at the END of your event
also, I highly suggest you to add an else statement in that on_command_error event which also prints other errors
"bot" is curly underlined, aka doesnt recognize. How do I fix that?
code?
code definitely from chatgpt 💀
@potent spear the main thing for me is to deal with the database
you already have an on_message, just remove lines 21 - 25
also, the repeat command doesn't make much sense, it should have at least ctx as first arg
and not message... check out the docs
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
also command has context object
why message and client
yeah, first and foremost, you shouldn't do any method in the on_ready event
guys atleast make an effort read the docs or atleast watch a old yt tutorial even those are better than current code rn here 
why? you may ask, because of a warning, stated in the docs
meaning that on_ready shouldn't be the event used to do things like "oh, let me set things up before my bot actually comes ready"
в моём коде сборная солянка из всего. я часто пробую потом оставляю

alternative: a setup_hook
https://discordpy.readthedocs.io/en/stable/migrating.html#asyncio-event-loop-changes
in my code there is a combined hodgepodge of everything. I often try then leave
imagine actually trying to learn before attempting
mhm, you shouldn't freestyle too much, or it will basically take longer to fix pre written code than writing new one
FIX first, then continue
so the best option here would be "send me the link of the docs" and then say what you don't understand about it instead of just avoiding it in general
NO
it will not work because it first of all is missing a decorator
and second of all, your main file has some errors
I already understood about the main file. I'm asking if I fix everything basically will it work or not
it is not necessary to make a reference to the main file in each message
ofc if you fix everything it'll work...
what ?
I answered your question
because of the abbreviation in the form of "ofc". I have a bad translation of your message
ofcourse
@potent spear can I make the command in another file ?
that wouldn't fix it, but sure
that is, an event with databases in one file. And the commands to them in another ??
sure... you can split it up however you like, as long as they're imported or just loaded like a cog
@potent spear in my cog. 4 files with commands
did you mean to add this?
await bot.process_commands(message)
@potent spear
that's only relevant for the on_message method if you don't use a listen decorator
try some stuff, you'll see for yourself
I just know that it needs to be used if event and commands are in the same file and you don't have a cog
no, as the documentation says, this only needs to be used in the main file if your on_message has the @bot.event() decorator. This has nothing to do with commands and events being in the same file
damn new respect for sniper so much patience 
Hello everyone
it's coming to an end
👋
when im use bot.send_message i have this error
ERROR discord.client Ignoring exception in on_message_delete
Traceback (most recent call last):
File "C:\Users\Saúl\PycharmProjects\pythonDiscordmusic\venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Saúl\PycharmProjects\pythonDiscordmusic\main.py", line 28, in on_message_delete
await bot.send_message(message.channel, "{}:{}".format(autor, contenido))
AttributeError: 'Bot' object has no attribute 'send_message'
do you know why i have this?
commendable efforts nonetheless
how many years old tutorial were u watching? thats deprecated long ago
saw that 
You're right, I didn't realize the video was from 2019
👍
Thanks
nevertheless, don't watch YT tutorials to learn this library, use official documentation
the lib changes too often for YT vids to be reliable / up-to-date
also, most implementations on there are bad
understand, I'll check it then, thank you very much friend
reminds me the discord.py github repo has a few examples u can refer them
basic stuff is still present there
!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.
https://paste.pythondiscord.com/tizuxahefe
Can someone tell me why EVERY command is not existent (not showing and not in integrations), despite there being 0 errors?
The only exception is the command, create_verify_button, and I would like to know why this is the case, what makes it still work and functional. All the existent buttons still work, but just all other commands than the create verify button do not show up / used
has anyone successfully added a rich presence with an image to their bot?
I see how to do it with just the text, but adding a caption thing makes the image go away
now im starting to doubt i had the image in the first place, i cant seem to get it back
Can someone help me with the tracker network api
I don't understand how to use the connection
to my knowledge rich presence has to be done client-side with IPC, and isnt available for gateway bots
https://discord.com/developers/docs/topics/gateway-events#update-presence
https://discord.com/developers/docs/topics/gateway-events#activity-object
Bots are only able to send
name,type, and optionallyurl.
thanks for your response
https://paste.pythondiscord.com/tizuxahefe
Can someone tell me why EVERY command is not existent (not showing and not in integrations), despite there being 0 errors?
The only exception is the command, create_verify_button, and I would like to know why this is the case, what makes it still work and functional. All the existent buttons still work, but just all other commands than the create verify button do not show up / used
are you checking in the right guild? i.e. whatever guild has the ID 547886184458616843, cause it seems to be written correctly for syncing to that guild
there might not be an "error" in your IDE, but there are definitely some bad implementations
most obvious one being the on_ready spaghetti
it is highly suggested to do all that stuff in a setup_hook https://discordpy.readthedocs.io/en/stable/migrating.html#asyncio-event-loop-changes instead
even better is syncing via command, but their on_ready is sufficient - boolean flags are preventing it from re-syncing twice and change_presence is acceptable since re-identifying resets your activity iirc
U mean incorrectly? But if it is i don’t think cuz it gives roles correctly and all cmd seek correctly
no its totally correct from what i see
Mhm
Alr
Alr thx
How would I sync via cmd
could be as barebones as writing an on_message and looking for a message from you saying to sync (it'll still receive message content if you DM / ping the bot)
or writing a slash command in your development guild and getting it synced once beforehand
either way the advantage is you only sync whenever you need to, rather than every time you restart the bot - there's a daily ratelimit on syncing so you'd want to avoid hitting it
I think syncing always on the setup_hook in the dev guild and make a sync guild for global syncs.
https://discord.com/developers/docs/interactions/application-commands#registering-a-command
There is a global rate limit of 200 application command creates per day, per guild
Thus not including guild syncs.
sidenote: put the presence in the constructor of your bot 😉
still means it could break for the dev guild if you restart too many times
changing 200 commands a day would be optimistic
So where super and intent thing is?
right...
you'll need the activity kwarg
20 commands + 10 restarts, doesnt sound too far fetched for someone not aware of the ratelimit, unless updates dont count against it?
Ik it I’m just doin this before that cuz I don’t know the name of those are for discord I just started discord coding
Probably will revamp code when I have time
those are not NEW commands though 🤔
But it was a rushed code for an event
Global syncs
Rn just trying to fix it
not the greatest mindset
It's a global ratelimit not specific.@hushed galleon
So I have to change the on ready thing and the pre scenes
😢 am busy most of time
so updates dont count? the note i linked seems ambiguous about that distinction
still, if you make a bad implementation and rewrite later, you'll have more work
rewrite first, then add new stuff / fix whatever
Eh, I’m solely doing this just to understand discord coding bit more and how it works as well as just doing my event for my server rn
updates do count, but you're not updating 10 command 20 times a day though, I'd think
No I meant if you sync to a dev guild it's not included. Only global syncs.
But yeah very true
Otherwise I would have reached it a long time ago.
anyways, I'd prevent that by just having a dev bot lol
that was a reply to sniper, for your message the note i linked explicitly says "per day, per guild", so doesnt that mean there's separate buckets for each guild / global commands? not just outright non-existent
So the problem is not based on the commands functions nothing like that just on the starting of the bot and the server limit that is causing it
Then it would most likely not count overwriting ones.
I don't think you have to worry about those ratelimits yet, at least, for what you have
d.py still sends every command's structure via a PUT request, and i have no knowledge to tell if their ratelimit distinguishes between no changes, some changes, and new commands
Hey @thin trout!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Ok
fair point, I'd make the command surely global once it's a finished product, I guess only then it counts towards your limit
Hey I am having a error
@bot.command(name='play', help='Plays a song from YouTube.')
async def play(ctx, url: str):
# Make sure the user is in a voice channel
if not ctx.author.voice:
await ctx.send("You must be in a voice channel to play music!")
return
# Join the user's voice channel
channel = ctx.author.voice.channel
await channel.connect()
# Play the YouTube video
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
song = info.get('url', None)
if song:
player = nextcord.PCMVolumeTransformer(nextcord.FFmpegAudio(url))
player.volume = 0.5
voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
# Send a message when the song starts playing
await ctx.send(f'Now playing: {info["title"]}')
i got this error, can someone help me?
https://paste.pythondiscord.com/iquhajorar
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
you might wanna type that AttributeError out in Google, you'll find something
your error is on line 41 in main.py, we'll have to see that file ofc
my guess is you're mixing up discord.py ButtonStyle object with the discord-py-interactions library - both libraries are designed to be standalone so you should only use one or the other
yt tutorial alert
or maybe an outdated copy pasted gh repo
Thanks guys for all ur help!
Someone know if there’s a complete guide or tutorial on how to create a complete music bot (private usage) that can support YouTube with link and song name and also Spotify with playlist link
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Im trying to implement autocomplete into my slash commands but whenever its in a cog the slash command seems to stop registering
maybe that has a different decorator? not sure, I don't use v2 stuff
I cant seem to find anything in the docs and the same format works in main.py but not in a cog
@nextcord.slash_command(name="driver", description="Get information about a current Formula One Driver")
async def driver(self, interaction: nextcord.Interaction, driver_arg: str = SlashOption(description="The driver to get information about", required=True)):
drivers = await handler.get_drivers(int(await handler.get_current_year())-1, 1)
for driver in drivers:
full_name = " ".join([driver["givenName"], driver["familyName"]])
if str(full_name).lower() == str(driver_arg).lower():
picture = await handler.get_driver_picture(full_name)
code = str(driver["code"])
embed = nextcord.Embed(title=f"{full_name} [{code}]")
embed.add_field(name="Nationality", value=str(driver["nationality"]))
embed.add_field(name="Date Of Birth", value=str(driver["dateOfBirth"]))
embed.add_field(name="Number", value=str(driver["permanentNumber"]))
embed.set_thumbnail(url=picture)
await interaction.response.send_message(embed=embed)
@driver.on_autocomplete("driver_arg")
async def driver(self, interaction: nextcord.Interaction, driver_arg: str):
drivers = await drivers()
if not driver_arg:
return await interaction.response.send_autocomplete(drivers)
get_closest_driver = [driver for driver in drivers if driver.lower().startswith(driver_arg.lower())]
await interaction.response.send_autocomplete(get_closest_driver)
heres my code if anyone notices anything that i dont
on message blocks the entire code from working discord.py
why
found
it is about await bot.process_commands(message)
Yes. Though we recommend changing your @client.event to @client.listen()
client ;-;
The unfortunate fact of the matter is people still call their bots client
😔
why did that start? yt tuts?
Most likely
i got a problem with viewing the class in the interaction.send
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout= None)
@discord.ui.button(label= "Create a Ticket", style=discord.ButtonStyle.blurple, custom_id= "ticket_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels, name = f"ticket{interaction.user.name}-{interaction.user.discriminator}")
if ticket is not None: await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}", ephemeral= True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
channel = await interaction.guild.create_text_channel(name = f"ticket-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=f"Ticket for {interaction.user}")
await channel.send(f"{interaction.user.mention} created a ticket!")
await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}", ephemeral= True)
@app_commands.command(name="ticketing", description="Launch the ticket system")
async def ticketing(self, ctx, interaction: discord.Interaction):
embed = discord.Embed(title= "Ticket tool", color=discord.Color.red())
await interaction.channel.send(embed=embed, view=ticket_launcher())
await interaction.response.send_message("Ticketing system launched", ephemeral= True)```
An application command inside a view? 
it was outside before
i just tried to put it inside the view because it wasn't working
That will make it "less work" lol
sorry i didn't know
Did you sync your commands?
yes
@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f"Synced {len(fmt)} commands.")
Did you run it?
can't run the ticket code
Also I'm pretty sure you need copy_global_to
it gaves me error
It would be helpful to know the error
whats that?
You're syncing to a guild, yet your command is global
It copies your global commands to a guild
tree = ctx.bot.tree
tree.copy_global_to(guild=ctx.guild)
await tree.sync(guild=ctx.guild)
where i have to put this code?
You just edit your existing code to reflect that
It's not meant to be a copy paste solution :P
You just need to .copy_global_to before you .sync
Or don't sync to a guild, or add a guild to your app commands
Is there a decorator for this to call, like has_permissions? I tried commands.has_permissions but it did not work
its slash commands
!d discord.app_commands.default_permissions I'd suggest using this instead of a check
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
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.
excellent work compared to your last code only thing you should change that's left is actually using a database instead of a json
define "goes down"?
like the slash command stop showing up, except one, which is the create_verify_button
no errors either? not sure what could be causing the "desync" 🤔
nope
I mean the only thing is this
But then that's the server's thing
mhm, I'm not really using v2 stuff, so I can't really tell
I don't see any command syncing in this code
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Uh i do it here i think
or is it not
line 276
so you're telling me your slash commands work for 2 hours, and then some disappear?
yes, all but one
i'd have to run it again for it to start working again for 2 hours, etc
but all buttons still work and that one cmd works too, create_verify_button
do you have the applications.commands scope for the bot?
ye
if i didnt have it, the slash cmds wouldnt work at all right
I can try re-inviting it?
if you're not changing anything, it's not worth it
alr
Not that I recognize
"await tree.sync"?
examples/app_commands/basic.py lines 22 to 28
# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)```
have you tried making your commands global instead of syncing them to a guild?
not yet
found the issue lol
ok
nah they have the tree in their global scope
commands disappearing after some time is really weird
ah yeah, mb
wouldn't change a thing
right
it doesn't show either
remove that self, not needed
so i'd prolly have to define it like this
yeah just showing if i put self it wouldnt work the color is gone
#currency system
connection = sqlite3.connect("currencysystem.db")
cursor = connection.cursor()
#table: balances
cursor.execute("CREATE TABLE IF NOT EXISTS balances (user_id INTEGER PRIMARY KEY, balance INTEGER)")
connection.commit()
cursor.execute('''CREATE TABLE IF NOT EXISTS items
(item_name TEXT, price INTEGER)''')
connection.commit()
should i remove the self.synced thing
@bot.slash_command(name="buy", description="Buy an Item from the Shop!")
@commands.cooldown(1, 10, commands.BucketType.user)
async def buy(ctx, item:Option(str, "Input the item name you wanted to purchase! (lowercase only)",
required=True), quantity: Option(int, "Input the quantity of the item you want to purchase.", required=True)):
cursor.execute("SELECT price FROM items WHERE item_name=?", (item,))
result = cursor.fetchone()
if result:
item_price = result[0]
user_id = ctx.author.id
cursor.execute("SELECT balance FROM balances WHERE user_id=?", (user_id,))
result = cursor.fetchone()
if result:
user_balance = result[0]
if user_balance >= (item_price * quantity):
cursor.execute("UPDATE balances SET balance = balance - ? WHERE user_id = ?", ((item_price * quantity), user_id))
for i in range(quantity):
cursor.execute("INSERT INTO inventory (user_id, item_name) VALUES (?, ?)", (user_id, item))
em = discord.Embed(title="You brought an item!", description=f"Purchase complete! {quantity} x {item} has been added to your inventory! :0")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
connection.commit()
else:
em = discord.Embed(title="You brought an item!", description=f"Insufficient Aww Pika Coins!")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
await ctx.respond("Oh no...Insufficient Aww Pika Coins!")
else:
em = discord.Embed(title="You brought an item!", description=f"Oh wait...You don't have an account. Please run `/balance` to create an account.")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
else:
em = discord.Embed(title="Your brought an item!", description=f"Oh wait...That item doesn't exist")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
👀
Not necessary since setup_hook only get called once
@bot.slash_command(name="inventory", description="Check your inventory!")
@commands.cooldown(1, 20, commands.BucketType.user)
async def inventory(ctx):
user_id = ctx.author.id
cursor.execute("SELECT item_name, COUNT(item_name) FROM inventory WHERE user_id = ? GROUP BY item_name", (user_id,))
result = cursor.fetchall()
if result:
items = ""
for item in result:
items += f"item name: {item[0]} amount: {item[1]}\n"
em = discord.Embed(title="Your inventory contains:", description=f"\n{items}")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.send(embed=em)
else:
em = discord.Embed(title="Your inventory contains:", description=f"Your inventory is empty.")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.send(embed=em)
!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.
alr
so i should change it
you could...
since setup_hook doesn't rerun like on_ready does
@slate swan use the above instead of sending several messages
Alr, same with the self.added right
If you're going to subclass the client, just define the tree in the init
right
It's not working doesn't explain anything
how would i do that
There's literally an example I just sent
💀
examples/app_commands/basic.py lines 10 to 20
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
currently i have this, so should I be removing line 278 and adding that ?
along with the client
aight
Alr, I just implemented it
I'll have to wait like 2 hours for the results, I'll let you know abt it later. Thanks though
i need help in my code
does anyone know how to set permission for a user
yes
then like 5 to 10m ago it stopped working
oh
okay, whats the paste site
okay
i need help how to reply to a message in discord.py
i tried ctx.reply and ctx.respond but it didnt work
anyone?
code (just this section): https://pastebin.com/is6MWXvR
pycord, sqlite3
Only the balance command is working. The database is created. But
cursor.execute('''CREATE TABLE IF NOT EXISTS items
(item_name TEXT, price INTEGER)''')
connection.commit()
this second table doesnt create
and the bet, buy and inventory, slash command does not work
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
pls help me here
can i see some of the code?
so i could help you better
umm ok
@client.slash_command(guild_ids=[guild_id], description="Test 1") async def hello(ctx): await ctx.reply("Hello")
Imagine replying to slash command
yes
yes
@fresh fern
^
yes
huh?
Depending on lib it's mostly inter.send or inter.response.send_message

look humanic?
what do i do
You can't "reply" to an interaction
^
What lib are you using
like if i type /hello so the bot should reply to my msg "Hello"
just use ctx.send in this case
That's prefix command then
you're trying to make the bot reply to an interaction, wouldn;t work just use ctx.send
i mean "reply"
ctx.reply
like im replying u guys
not working
the tutorial guy used ctx.respond which is also not working
try this
what error are u getting
it doesnt work doesnt mean the thing doesnt work
maybe other thing is not working
like me screwing up my database for one month straight
@fresh fern you can only reply in prefix command, what you currently have is slash command
prefix command means
example: m.help
slash commands means
/help
And in slash command you can only respond to interaction
i have prefix command but i wanna shift to slash command
There is no message
error - Command raised an exception: AttributeError: 'Interaction' object has no attribute 'respond'
What lib are you using
Discord
!d discord
Rename ctx to inter and do inter.response.send_message
ok
no but im having ctx as a parameter
so nothing will happen after changing the name if the parameter
lemme try
👀 i mean we learn through spoon feed sometimes
cuz some new concept are hard to understand without examples
after this the slash command vanished
anyone gonna help me here? ._.
Name ctx doesn't follow informal convention of naming Context instances ctx and Interaction inter/interaction
You need to add decorator to this function, how are you expecting lib to recognise the function is a slash command callback
In this concrete case it's literal spoonfeeding, not even code example
inter thing not worked
i guess i have to stay on prefix
You could just switch to disnake
and rework on the whole thing
Cause it's easy for non-advanced users
hmm
Rewriting code is good
yes
yea
not until u finished 90% of the bot with 35 commands that has a total of 6k lines of code
Cause you replace constructions you created while you were stupid with new more effecient and elegant stuff
I did that like 5 times
i mean you are right
but if they are all intertwined to one another
u get fed up trying to fix one error but ended up creating a whole new one
Ewww no sub types
I use sub types in this situation for my ide to type hint my code
exenifix prolly just lazy to type
@bot.slash_command(name="bet", description="Gamble some money!")
@commands.cooldown(1, 20, commands.BucketType.user)
async def bet(ctx, amount:Option(int, "Input the amount you wanna bet.", required=True)):
balance = handle_balance(ctx.author.id)
if amount > balance:
em = discord.Embed(title="Your gambled some money! :0", description=f"Oh wait... You do not have enough money to make that bet.")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
return
outcome = random.choice(["True", "False"]) # generate outcome randomly
if outcome == "True":
cursor.execute("UPDATE balances SET balance = ? WHERE user_id = ?", (2 * amount, user_id))
conn.commit()
em = discord.Embed(title="Your gambled some money! :0", description=f"You won {2 * amount} AwwPika Coins!")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
if outcome == "False":
cursor.execute("UPDATE balances SET balance = ? WHERE user_id = ?", (-amount, user_id))
conn.commit()
em = discord.Embed(title="Your gambled some money! :0", description=f"You lost {amount} AwwPika Coins!")
em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
await ctx.respond(embed=em)
my balance slash command works well.. how come this bet command not work?
if user win they get 2x the amount betted
if user lose they lose all the amount betted
this is sqlite3 and im using pycord... pls help here :))
the database works completed fine... it shows "Application does not respond" when i run the slash command....
theres no error... can u check the code for me?
no...
No
💀
You're more prone to running into blocking-related issues with the standard sqlite3 library though.
Hello, I've faced with one problem. Can somebody help me? The script was created by AI. And it's completely fine just in the last step it crashes, because of stale element. PLEAAAAASE
Consider aiosqlite or asqlite instead
Find the message input field
def new_func(driver):
message_input = driver.find_element('xpath','/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/div[1]/div/div[2]/div[3]/div[2]/main/form/div/div[1]/div/div[3]/div/div[2]/div')
return message_input
message_input = new_func(driver)
time.sleep(15)
Iterate over the messages
for message in messages[:100]:
# Send the message
message_input.send_keys(message)
time.sleep(7)
message_input.send_keys(Keys.RETURN)
time.sleep(19)
message_enter = driver.find_element('xpath','/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/div[1]/div/div[2]/div[3]/div/main/form/div/div[2]/div/div[2]/div/div/div/span[1]/span/span')
message_enter.send_keys(Keys.RETURN)
time.sleep(5)
message_input = new_func(driver) # re-find element
# Wait for 120 seconds before sending another message
time.sleep(6)
Close the browser
driver.close()
It doesn't second message after first iteration
I probably don't have to guess which AI generated this
is the code correct?
And is that for self-bot purposes?
em.set_footer(icon_url = ctx.author.avatar) I think you need avatar.url here
It's just for my use
I think the best solution would be to not use an AI to write your bot's code.
I am too close to the solution. I changed this little script over 5 hours yersteday
And still can't resolve it fully, after first iteration I have this error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=109.0.5414.87)
no need it works for all my other commands
the icon_url is converted to str(provided value) internally by discord.py
and __str__ of Asset returns it's url, so that works
I didn't know that :-)
Thanks
That man looks like an absolute beginner I would confuse him even more, also they are called typehints
- idk dpy interaction command-specific type 🤓
!d disnake.ApplicationCommandInteraction disnake best lib
class disnake.ApplicationCommandInteraction```
Represents an interaction with an application command.
Current examples are slash commands, user commands and message commands.
New in version 2.1.
dpy has only one interaction class and it's discord.Interaction, sucks
Tried lightsail for the last week, it's functioning really bad 😂
you have any idea why?
it just crashes sometimes and stop working, I have to reboot it from the AWS console
can someone help me here?
https://pastebin.com/AvtMr5Yh
pycord and sqlite3
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the table is created successfully and somehow just this single command doesnt work, both balance and buy command works well
can anyone help me pls? 
Hello, Anybody can help me with this?
after first successful message it crashes
https://linkode.org/#y9qHayYTBufgxRxBr1JKT2 After first iteration it's crashing
I have that error with stale element:
https://linkode.org/#4uzdrKysAZxKY2nmESYzP1
Linkode is the useful pastebin!
do you know what channel this is?
Yes, it's bot if you are about channel in script
it's not anything about discord bots and the error is clearly not
Sorry Ash, I'm new here. I tried to make bot for Discord to use bot in Discord, for personal use
unable to open 
that's not anything related to discord bots, you might want to claim a help channel ( #❓|how-to-get-help ) and ask your question there
wdym it is able to open... i just checked it again ..
idk, forgib
imagine not using hastebin itself
......
but whats the error?
Hi, best way to debug memory leaks in the discord bot?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
no error
Do I take the cake for least readable discord.py code yet?
stats_embed.add_field(name='Top 5 Text Channels:', value='\n'.join([f'> {ctx.guild.get_channel(entry[0]).mention if ctx.guild.get_channel(entry[0]) else "`Unknown Channel`"}**: {"{:,}".format(entry[1])} Messages**' for entry in sorted_message_count_by_channel[:5]]))
nope
1 moment
Oh dear.
List comp with .join 
Use generator expression
can someone help me make a inventory slash command? with pycord and sqlite3
ive been trying for so long... all my balance / buy / currency commands / database all is working... but somehow i just cant find a way to make a inventory command 😐 😭
hello, how to add options in discord.py slash command?
what i have:
@bot.hybrid_command(name = "Shop", description = "Give your coins in exchange for an item")
async def shop(ctx, type="basic"): #codes for shop```
what i want is like the one shown in pic
examples/app_commands/transformers.py lines 80 to 87
# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.
# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
can someone pls help 😦
Provide an error then
Error: "Application does not respond"
tysm
i even tried to put error handling code and it give me nothing...
its just this single command of my entire code is not working :/
Then there's an error
How can anyone tell what's the error if you don't even know it's there
It literally shows nothing in console and shows no error... like i said i even tried adding in error handlers in this section of the code... and still no error shown.... HOW IM I EVEN SUPPOSED TO FIND AN ERROR WHEN THERE ISNT ONE?
😭
sure
How come there's no error but it's not working, what could it be? A ghost maybe?
heres' the code:
https://pastebin.com/divz6i3L
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the buy command works fine
it is pycord and sqlite3
embed=em works fine
check line 64, it works for buy command
That's the first 2 errors
https://pastebin.com/j98nQAJu
edited heres the new code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
"Application does not respond" when i run /inventory command
okie
still same error
i replaced it to await ctx.reply()
i dont think thats the issue
Is it better to use use asyncio and the aiohttp library instead of requests to reduce the time for a command?
I don't know if aiohttp is any faster than requests if you're going to make a single request, but yeah, you should use aiohttp because requests is blocking
I want to make multiple API calls at the same time, rather than waiting for each one to complete before making the next one
async code isn't essentially faster than sync code
but yeah you're on the bright side when using async code in an async environment
do you want the api call to return a value?
or is it just fire and forget
It should return new data each time
!d asyncio.gather
awaitable asyncio.gather(*aws, return_exceptions=False)```
Run [awaitable objects](https://docs.python.org/3/library/asyncio-task.html#asyncio-awaitables) in the *aws* sequence *concurrently*.
If any awaitable in *aws* is a coroutine, it is automatically scheduled as a Task.
If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in *aws*.
If *return\_exceptions* is `False` (default), the first raised exception is immediately propagated to the task that awaits on `gather()`. Other awaitables in the *aws* sequence **won’t be cancelled** and will continue to run.
If *return\_exceptions* is `True`, exceptions are treated the same as successful results, and aggregated in the result list.
If `gather()` is *cancelled*, all submitted awaitables (that have not completed yet) are also *cancelled*.
Example: !showranks (shows ranks for all users in that specific voice channel)
Next time you run the command, it should receive new data from the API
Yo btw guys for some reason on_member_join is not work
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
@bot.event
async def on_member_join(member):
print('testing')
welcome_message = discord.Embed(
title='Welcome to the server!',
description=f'Hello {member.mention}, we are glad you are here!',
color=discord.Color.green()
)
channel = bot.get_channel(1042913508779634770) # Replace 'id' with the channel ID you want the welcome message to be sent in
await channel.send(embed=welcome_message)
bot.run('TOKEN') # Replace 'TOKEN' with your bot's token
Looks like you created intents but didn't pass it in anywhere
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
okay thanks i forgor 💀
See how in this codeblock they included intents=intents?
please tell me how it is calculated. Well , like how much exp does it take to level up ?
if cur_xp >= round((4 * (cur_lvl ** 3)) / 5):
just don't need me to throw documentation with a description for round()
It's depends on how hard you want it to take to level up 🤷
how exactly is the level calculated?!
@naive briar 4 * (cur_lvl ** 3) / 5
that 's how it counts ?
there's no fixed way, every bot has it's own calculations
for example, I want to change it so that 100 messages are needed to get level 1, twice as many for level 2, and so on
https://github.com/Mee6/Mee6-documentation/blob/master/docs/levels_xp.md mee6 for instance uses this
documentation for Mee6 discord bot. Contribute to Mee6/Mee6-documentation development by creating an account on GitHub.
That doesn't sound like it requires any math
now that's just some floor division
!e ```py
a = 100
b = 235
c = 1295
print(a//100, b//100, c//100)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 2 12
OMG. I just want to understand how it works, how to understand how much exp is needed for up level. And whether it is possible to change it somehow.
lol bro just use some progression formula for ease just use some ap formula
Why is the cogs not showing in the help commands and I can't use them as a command?
#main.py
@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def load(ctx, extension: str = None) -> None:
""" Loads a cog.
:param extension: The cog. """
await ctx.message.delete()
if not extension:
return await ctx.send("**Inform the cog!**")
client.load_extension(f'cogs.{extension}')
return await ctx.send(f"**{extension} loaded!**", delete_after=3)
@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def unload(ctx, extension: str = None) -> None:
""" Unloads a cog.
:param extension: The cog. """
await ctx.message.delete()
if not extension:
return await ctx.send("**Inform the cog!**")
client.unload_extension(f'cogs.{extension}')
return await ctx.send(f"**{extension} unloaded!**", delete_after=3)
@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def reload(ctx, extension: str = None) -> None:
""" Reloads a cog.
:param extension: The cog. """
await ctx.message.delete()
if not extension:
return await ctx.send("**Inform the cog!**")
client.unload_extension(f'cogs.{extension}')
client.load_extension(f'cogs.{extension}')
return await ctx.send(f"**{extension} reloaded!**", delete_after=3)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
#information.py
import discord
from discord.ext import commands
class Information(commands.Cog):
"""Information Cog."""
def __init__(self, client):
self.client = client
# Events
@commands.Cog.listener()
async def on_ready(self):
print('information cog is ready!')
# Commands
..............
def setup(client):
client.add_cog(Information(client))
cog load is now async
?
The type hint is when you use inter arg in the function but when defining is sub type
@shrewd apex there are examples where only normal ones are given, and not as in the documentation ???
Defining what
def func(alex: str):
Never seen anyone using "subtype" term and I am still unsure what you mean by it
sub type is the name for defining function args type
type hinting is when you call the arg in function
IIRC
Mm where's that info from
I've always seen subtype used in the context that a type that inherits another is a "subtype"
but not like this
Yeah that makes sense
Fair enough
Can you explain about it please?
I heard something about new async load and I didn't understand
How can I fix it that it will show on help command and it 'll work?
yea thats all wrong
What would you use if you want to return a value?
Why is the the bot not staying online with the following function?
time.sleep(5)
schedule.every(3600).seconds.do(update_elo_ratings)
while True:
schedule.run_pending()
time.sleep(10)```
Is there anything with this function that makes the bot no staying online?
It's updating the elo, the only issue is that the bot is not online as it supposed to be.
Traceback (most recent call last):
File "main.py", line 77, in <module>
bot.run(os.getenv('Token'))
File "/home/runner/juicebot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
``` It keeps giving me this error.
maybe print the token and make sure it's valid
is that the full traceback you got?
why do you need to transfer it?
I just want to remove this command from the file where it is located. And transfer to the file gle I have the command /prof
That and a essay of html and js 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.
if it's too long
@vocal snow Can you give me an example of a cog command? pls
from discord.ext import commands
class MyCog(commands.Cog):
@commands.command()
async def foo(self, ctx):
...
@vocal snow Can you please look at my code and try to help me with it?
are you getting an error?
No
it is not showing me the command on help cmd and it is not work! @vocal snow
None errors
cog is now async load he is loading sync
load the cog async
ik let him figure it out
i even linked migration docs but it seems no use
why
async def setup(bot):
await bot.add_cog(Cog(bot))
await bot.load_extension('cogs.Cog')
and why client is a problem?
Bruh why is discord.ext.commands so weird
because you aren't trying to override the bot's internal on_message event, which is what the event decorator does
what's weird?
hm
The arguments passed. You can grab all the arguments and place them in a tuble uses *args but it breaks when you use qoutes in your arguments.
See:
discord.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '「', in non-quoted string
「
、
These things break it
Why does it do this :v
@bot.command()
async def translate(ctx, *args):
how do i make a slash command
if you're looking to get all the arguments split on space while ignoring parsing nuances, you might want to use a keyword-only argument and then .split() it
which library?
discord.js
Sir this is a Python server
i couldn't find any js server 😭
Yeah gimme a second.
oh tysm
Why?
discord.errors.HTTPException: 429 Too Many Requests
It's worthless
Uptime robot...
you're being ratelimited; you should make sure you don't send make too many API calls at once
It’s this.
It pings the web server of the bot every 15 minutes but it hasn’t gave me that error until I turn it to 5 minutes.
member = ctx.author if not member else member
member_id = str(member.id)
if not member_id in self.users:
await ctx.send("участник не имеет уровня")
else:
embed = discord.Embed(colour=0x2F3136)
embed.set_author(name="Вы были замучены на сервера")
embed.set_author(name= f"Уровень - {member}")
embed.add_field(name= 'Уровень', value= self.users[member_id]["level"])
embed.add_field(name= 'Опыт', value= self.users[member_id]["exp"])
await ctx.send(embed=embed)```
how to transfer this information from embed to another file located in cog?
So using qoutes are considered keyword arguments in the library?
use the pickle module to save the information to a file, and then use pickle.load() to load the information from the file into another cog or script.
import pickle
# Saving the information to a file
with open('member_info.pickle', 'wb') as handle:
pickle.dump(self.users[member_id], handle, protocol=pickle.HIGHEST_PROTOCOL)
# Loading the information from the file
with open('member_info.pickle', 'rb') as handle:
loaded_member_info = pickle.load(handle)
Only the cogs is not working.
pickle.dump(self.users[member_id]["level"], handle, protocol=pickle.HIGHEST_PROTOCOL)
is that possible ?
yes @errant pecan
import pickle
# Saving the level to a file
with open('member_level.pickle', 'wb') as handle:
pickle.dump(self.users[member_id]["level"], handle, protocol=pickle.HIGHEST_PROTOCOL)
# Loading the level from the file
with open('member_level.pickle', 'rb') as handle:
loaded_member_level = pickle.load(handle)
import pygame
class Player(pygame.sprite.Sprite):
def init(self,width, height, pos_x,pos_y,color):
super().init()
self.image = pygame.Surface(width,height)
self.image.fill(color)
self.rect = self.image.get_rect()
#general setup
pygame.init()
#game screen
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode(screen_width,screen_height)
player = crosshair(50,50,100,100,(255,255,255))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.flip()
This will save the ***self.users[member_id]["level"] *** value to a file called member_level.pickle , and then load it into the loaded_member_level variable which then u can use in another cog or script
Wrong channel?
so which one
stupid python. It would be fine to make a transfer. No they will do incomprehensible stuff
what
it's all complicated.
most things are till u learn it really.
but once u learn it, it can be very helpful
and less complicated
just like anything u learn
added u so we can chat
I tried it and it didn't work out
add me real quick
How does this python bot manage subfolders in the cogs folder?
I see that it has some folders in the extensions folder, but I can't follow the code enough to find how it loads the sub folders. The closest I can get is self.bot.all_extensions, but that looks external
https://github.com/python-discord/bot-core/blob/08a7a742f61d655c2bd4fd02b95bb70e3d4b815e/pydis_core/utils/_extensions.py#L28
looks like it uses this, which in turn uses pkgutil.walk_packages to recursively find packages
pydis_core/utils/_extensions.py line 28
def walk_extensions(module: types.ModuleType) -> frozenset[str]:```
Hi there, I'm getting a problem with this code... the bot works fine, theres no errors, but it simply stops responding in the discord chat once I untag the part at the bottom... How can I fix this? ```py
@client.event
async def on_message(message):
if message.author == client.user:
return
print(f"Server: {message.guild.name} Channel: {message.channel.name} User: {message.author} : {message.content}")
#Problem is from here onwards
server_id = str(message.guild.id)
channel_id = str(message.channel.id)
user_id = str(message.author.id)
if server_id not in messages:
messages[server_id] = {}
if channel_id not in messages[server_id]:
messages[server_id][channel_id] = {}
if user_id not in messages[server_id][channel_id]:
messages[server_id][channel_id][user_id] = []
messages[server_id][channel_id][user_id].append(message.content)
with open("messages.json", "w") as f:
json.dump(messages, f)
I see. Thanks!
What is the if statement for a member that has been moved from one voice channel to another?
I remember it has to deal with if before.channel == None and after.channel != None: something like this
@naive briar it doesn’t work
Can somebody please tell me why the bot never goes online after adding this code?
def update_elo_ratings():
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
time.sleep(2)
while True:
update_elo_ratings()
time.sleep(600)```
Should I use the threading library to create a new thread for the while True loop?
!d discord.ext.tasks.Loop
class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.
The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
Sorry but do you know the solution to this problem?
Yeah, that's what I linked
You mean like this?
@tasks.loop(minutes=10)
async def update_elo_ratings():
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(2)
update_elo_ratings.start()```
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited```
Did you do .start() inside a function?
Or is it just free-floating
My bad, free floating. Should I use:
@client.event
async def on_ready():
update_elo_ratings.start()
client.loop.create_task(update_elo_ratings())
What's the .create_task doing in there?
So
@client.event
async def on_ready():
update_elo_ratings.start()
# Set the bot's activity
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
await client.change_presence(activity=activity)
print('Bot is ready!')
@tasks.loop(minutes=10.0)
async def update_elo_ratings():
# Get all the users in the collection
users = collection.find()
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
await asyncio.sleep(2)```
please use that activity in the constructor of your bot, not in on_ready
(it has an activity= kwarg)
also, you should start tasks in a setup_hook 🙂
=> on_ready is to be avoided in general
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
https://paste.pythondiscord.com/enehoyevax
slash cmd disappearing after few hours, but everything works completely fine before that happens. One command still works: /create_verify_button
How do I do that?
https://discordpy.readthedocs.io/en/stable/migrating.html#asyncio-event-loop-changes
second quick example
=> you subclass your client / bot
add the setup hook
start the task in there
I think I know the problem, when I use /create_verify_button, it creates 2 embeds with 2 buttons. One of them is updated (second one, the one below) while the other one is super outdated (the first one)
That might be why only that cmd shows up
@potent spear do u happen to know anything abt this?
Mhm, you have 2 instances of your bot running
Yeahhhhh
How do i remove view
Remove the until=
So just …timeout(short_timeout, reason=“yes”)
Wdym? How do you stop the old instance?
That yeah
The view is updated i think, just the instance I meant
I only had add view to the create verify button button
Before I added more add_view()'s
So I was thinking it might have been staggered somehow
It doesn't start the task.
class Client(discord.Client):
async def setup_hook(self):
update_elo_ratings.start()
client = commands.Bot(command_prefix = ['!', '>'], intents = INTENTS, help_command=None)```
That’s because you’re not using your subclassed bot
Sorry but how do I do that?
That’s basic python
Ctrl+f subclassed bot here, you’ll find examples
do u know how to remove old instance
Well, how do you usually run your bot?
Check if you’re not accidentally running it in some other task… if you have no idea, just rebooting whatever you’re hosting it on will do, should stop ALL instances
i press run
On…
on the server I use, and when testing I use visual studio code
but visual studio code I have ran it even after the update
ok
it might be runingo on studio code, how would i stop an instance on thre?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, help_command=None)```
Mhm, seems about right. Try and see
What is the super().init(*args, **kwargs) for?
Not really needed in your case, would only be handy if you’re overwriting the constructor and adding extra attributes etc to your subclass
Do you know how I can stop the code in visual studio code?
take a screenshot of your terminal please
🤦♂️ when you'd run it
then a terminal output screen would pop up
on the right, you'll see that most likely, a few of these terminals are opened
just close them all with the 🗑️
Yeah that's what I do
Should I add activity under class MyClient(commands.Bot) as well?
Since you told me to use the activity in the constructor of my bot
not needed, you can pass that in MyClient(...) like you did with commands.Bot(...)
@potent spear I clicked the trash can thing already since I have not used the visual studios in a long time and it still does not work
So,
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
# Set the bot's activity
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)
@client.event
async def on_ready():
print('Bot is ready!')```
or am I wrong?
Just test it
looks good
you could even put that on_ready in your subclassed bot if you'd want to... (you don't need that even decorator anymore then)
Sorry I'm confused 😅 You told me not to use it in here:
@client.event
async def on_ready():
# Set the bot's activity
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
await client.change_presence(activity=activity)
print('Bot is ready!')```
correct
just do
class MyClient(...):
.........
async on_ready(self):
print("ready")```
Yeah, I just tested and it's not the visual studio code issue. I'll try restarting my hosting server
sure, you never mentioned a host server, so there's that
Okay
also if it was the same server that was causing the issue, how come the same server can cause more than one views, like when I use create verify thing I said that it shows 2 embeds and 2 buttons
Does that mean views save if on the same server?
you can run multiple instances of the same bot if you don't quit the previous one
Oh, I meant that I have a separate server than the visual code
To rerun my thing, I press "stop" on the server
well, restarting that will most likely stop all instances
yeah, so that "server" has multiple terminals opened or whatever
Yeah but then does that mean the more I run in the future the same problem will arise*
Oh ok so I'd have to do the thing now to re-fix it everytime instead of pressing stop
just quit your previous instance to avoid that issue
no, not if you quit the previous bot
Ah, I just reinstalled the server and it still shows 2 buttons
how do I quit it?
is the server even running AN instance?
dont think so
then your pc is the problem... weren't you sometimes running the bot on there too?
on where?
The first or second one?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready():
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
await client.change_presence(activity=activity)
print('Bot is ready!')
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, help_command=None)```
```python
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready():
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
print('Bot is ready!')
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
second one, but the activity shit should just be defined above your client = ... line
well, those "rare times" Ig are the culprit, just closing the terminal in vsc doesn't quit it, you have to stop it too, or closing vsc quits it too most likely
Can you show me an example please?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready():
print('Bot is ready!')
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
ok
So my pc runs the code at any time?
Thanks. One more question, shouldn't print('Bot is ready!') be with two additional spaces? Or it doesn't matter?
if you have vsc open and you forgot to quit, yes
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready():
print('Bot is ready!')```
yeah, you can format through your IDE
yup, I just typed it in the textbox here, so it isn't aligned or indented or whatever
Gotcha. Thank you!
Where do I look to quit it? In my folder?
top right might have some powershells or whatever open of your previous bot
ok, I think I quit it
Let me restart my bot
It still creates 2 verify buttons
2 embeds too
hello, can someone help my bot isnt setting user permissions for a channel
if str(message.author) == bot_name:
return
if isinstance(message.channel, discord.DMChannel):
name = 'MODMAIL'
guild = bot.get_guild(991639918243741757)
guild = discord.utils.get(guild.categories, name=name)
channels = []
for channel in guild.channels:
channels.append(channel.name)
if str(message.author.id) in channels:
channel = discord.utils.get(guild.channels, name=f"{message.author.id}")
await message.author.send(f"You already have a ticket open! <#{channel.id}>")
else:
guild = await guild.create_text_channel(name=f"{message.author.id}")
await guild.set_permissions(message.author, send_messages=True)
await guild.set_permissions(message.author, read_messages=True)
await guild.set_permissions(message.author, read_message_history=True)
channel = bot.get_channel(guild.id)
await channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
await message.author.send(f"I have created you a ticket in Lab Games <#{guild.id}>")
one unupdated, one updated
[2023-01-13 01:35:19] [ERROR ] discord.client: Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: MyClient.on_ready() takes 0 positional arguments but 1 was given```
remove the self
I'd say, just regenerate a token in that case, all your previous bots will stop
you're using guild = guild.create_text_channel(...), while you mean new_text_channel
fix those variables and you'll find the error
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
^^^^^^^^^^^^^^^^^
TypeError: MyClient.setup_hook() takes 0 positional arguments but 1 was given```
same solution
I removed it
good, then that should be fixed
there is not new_text_channel
read what I said please
i did
I said, you're using
guild = guild.create_text_channel(...)
this makes no sense
use
new_text_channel = guild.create_text_channel(...)
oh
get it? then rewrite the other bit and the error will speak for itself
yea, lemme try
Well it's not
new error + current code?
class MyClient(commands.Bot):
async def setup_hook():
update_elo_ratings.start()
async def on_ready():
print('Bot is ready!')
activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
yup, run that, should be fine
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 589, in login
await self.setup_hook()
^^^^^^^^^^^^^^^^^
TypeError: MyClient.setup_hook() takes 0 positional arguments but 1 was given```
you saved, right?
Ofc
*my bad
(self) should be inside the setup_hook() as well as in on_ready()
Working 👍
ok
good
async def on_message(message: discord.Message):
if str(message.author) == bot_name:
return
if isinstance(message.channel, discord.DMChannel):
name = 'MODMAIL'
guild = bot.get_guild(1062991670674731098)
guild = discord.utils.get(guild.categories, name=name)
channels = []
for channel in guild.channels:
channels.append(channel.name)
if str(message.author.id) in channels:
channel = discord.utils.get(guild.channels, name=f"{message.author.id}")
await message.author.send(f"You already have a ticket open! <#{channel.id}>")
else:
new_text_channel = await guild.create_text_channel(name=f"{message.author.id}")
await new_text_channel.set_permissions(message.author, send_messages=True)
await new_text_channel.set_permissions(message.author, read_messages=True)
await new_text_channel.set_permissions(message.author, read_message_history=True)
channel = bot.get_channel(new_text_channel.id)
await channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
its still not working
since none of my discussions/forum responses are ever responded to (LIKE USUAL. doesnt matter if its in discord or not)
[Discord PY 2.0, PY 3.11] Text version of Hybrid command wont work with arguments
simple explaination: arguments work fine in the slash command but not in the text command it'self
Command Code:
@client.hybrid_command(name="setstatus", with_app_command=True, description="Change the status of the bot")
async def setstatus(self, ctx: commands.Context, type: int, status: str):
await ctx.reply(f"Set the status to '{str(status)}' with activity type to **{int(type)}**")
await client.change_presence(activity=discord.Activity(type=int(type), name=str(status)))
(I dont get any error messages as only the slash command itself works but not the textcommand of itself)
look at this
channel = bot.get_channel(new_text_channel.id)
do you realize how redundant this is?
wow discord updated the python code blocks
any errors?
android mobile only
on pc too
will anyone actually help ?!
none
!d discord.ext.commands.Context.send
even in my log file
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...
@potent spear
I wouldn't use type as an argument name first of all, that's a reserved variable name
That requires minimum effort of research
should i just use like statustype ?
are you in a cog?
no.
then the self parameter is not needed
i am currently not in a cog
let's shorten this a bit, alr?
channels = []
for channel in guild.channels:
channels.append(channel.name)
if str(message.author.id) in channels:
# should become
channel = discord.utils.get(guild.channels, name=str(message.author.id))
if channel:```
remove self & the kwarg with_app_command=True is redundant, as this is default True
also str(status) is redundant, since status is already a string
alright
wait so i dont need with app command?
that's default true...
since hybrid is both slash and normal
that's default...
I mean, you don't have to remove it
Not like it's gonna break everything if it's there
less is more
unless you make stuff unreadable or just more complicated
pov: unorganized/messy code
it all starts with bad variable names
that's a mess to debug
anyways, is ther any other errors within my code?
if str(message.author) == bot_name:
return
if isinstance(message.channel, discord.DMChannel):
name = 'MODMAIL'
guild = bot.get_guild(1062991670674731098)
guild = discord.utils.get(guild.categories, name=name)
channels = []
for channel in guild.channels:
channels.append(channel.name)
if str(message.author.id) in channels:
await message.author.send(f"You already have a ticket open! <#{channel.id}>")
pass
channel = discord.utils.get(guild.channels, name=str(message.author.id))
if channel:
try:
new_text_channel = await guild.create_text_channel(name=f"{message.author.id}")
await new_text_channel.set_permissions(message.author, send_messages=True)
await new_text_channel.set_permissions(message.author, read_messages=True)
await new_text_channel.set_permissions(message.author, read_message_history=True)
await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
except Exception as e:
print(e)
what is that whole for loop stuff supposed to check?
what does it currently look like?
@client.hybrid_command(name="setstatus", description="Change the status of the bot")
async def setstatus(ctx: commands.Context, statustype: int, status: str):
await ctx.reply(f"Set the status to '{status}' with activity type to **{statustype}**")
await client.change_presence(activity=discord.Activity(type=statustype), name=status)
if the user already has a ticket open with their user id as a name
changed the "type" variable
seams neat, does it work?
gonna see if the text cmd works
you can use an alias or something I guess to still make it work as "type" for slash commands
ah, good
still, close
if message.author == bot.user:
return
if isinstance(message.channel, discord.DMChannel):
category_name = 'MODMAIL'
guild = bot.get_guild(1062991670674731098)
modmail_category = discord.utils.get(guild.categories, name=category_name)
author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
if author_modmail_channel is None:
return
# ...
go ahead
ofc, not perfect format, but you can do that with your IDE
did you sync?
i j want it to work
yeah
it was working yesterday then it randomly stopped
why don't you use the category ID instead?
i couldnt find a way to do that
Hey I have a question
right click the category, copy the ID
you can use get_channel on that too
no i mean in the code
About pde, heat equations analytical solution. Where to ask?
I had to re add with_app command because the whole cmd itself wasnt working
modmail_category = guild.get_channel(<category_channel_id>)
it only typed a response and did nothing else
what "else" should it have done?
change status type and whatever string
ah, i didnt know you could use that for categorys
yeah, a category is a CategoryChannel object
so this made your bot reply, but not change its presence? (and would only work with slash commands?)
well it changes the status type and the stauts itself is a string, and it only worked with a slash command
do "normal" commands work? aka non-hybrid nor slash commands
if message.author == bot.user:
return
if isinstance(message.channel, discord.DMChannel):
guild = bot.get_guild(1062991670674731098)
modmail_category = guild.get_channel(1062991672465698914)
author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
if author_modmail_channel is None:
try:
new_text_channel = await guild.create_text_channel(name=f"{message.author.id}")
await new_text_channel.set_permissions(message.author, send_messages=True)
await new_text_channel.set_permissions(message.author, read_messages=True)
await new_text_channel.set_permissions(message.author, read_message_history=True)
await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
except Exception as e:
print(e)
return
await message.author.send(f"You already have a ticket open! <#{author_modmail_channel.id}>")
yeah I converted my setstatus code from a normal text commadn to a hybrid
i think i did that right
when it was a normal, it worked just fine
looks great! works?
main problem is, if i make a hyrbdi command without any sort of arguments, it works fine, both slash and text command
however if i add arguements, it stops working as a text cmd
Can I use other time units for @tasks.loop(minutes=30.0) example @tasks.loop(hours=12)?
yes...
i explained the problem in context
now it doesnt even put it in the right category
do you have error handlers?
oh, not yet
well your create_text_channel method is incorrect
you have to add a kwarg
category = mod_category or whatever it's called
not needed, especially now
maybe I need to see the whole code, I think there's more to it
!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.
create_category_channel?
no
create_text_channel(......, category = <your modmail category> )
oh im stupid
import discord, typing
from discord.ext import commands
from discord import app_commands
from typing import Union
import random
client = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
Token = "<censored for various reasons>"
@client.event
async def on_ready():
await client.change_presence(activity=discord.Activity(type=0, name="Splatoon 3"))
print("Bot is ready")
try:
synced = await client.tree.sync()
print("Slash commands should have been synced")
except Exception as e:
print("I wasnt able to sync slash commands ;w;")
# hybrid commands
@client.hybrid_command(name="ping", description="shows bot ping, nothing else")
async def ping(ctx: commands.Context):
await ctx.reply(f"pong! bot ping is {round(client.latency * 1000)} ms")
@client.hybrid_command(name="test", description="A test Hybrid command.")
async def test(ctx: commands.Context):
await ctx.reply("This is a test hybrid command.")
@client.hybrid_command(name="setstatus", with_app_command=True, description="Change the status of the bot")
async def setstatus(ctx: commands.Context, statustype: int, status: str):
await ctx.reply(f"Set the status to '{str(status)}' with activity type to **{int(statustype)}**")
await client.change_presence(activity=discord.Activity(type=int(statustype), name=str(status)))
client.run(Token)
for the int() and str() it sstopped aworking safter i removed it
ok, so first things first, you don't wanna sync in on_ready, do that in a setup_hook
#discord-bots message
also, are your intents enabled in the dev portal?
okay it works now but its only setting await new_text_channel.set_permissions(message.author, read_message_history=True) permission
full code?
Does it really matter if you use @tasks.loop(minutes=720.0) or @tasks.loop(hours=12)?
btw, you can do a sexy all-in-one, where you use the overwrites kwarg in create_text_channel
if message.author == bot.user:
return
if isinstance(message.channel, discord.DMChannel):
guild = bot.get_guild(1062991670674731098)
modmail_category = guild.get_channel(1062991672465698914)
author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
if author_modmail_channel is None:
try:
new_text_channel = await guild.create_text_channel(name=f"{message.author.id}", category=modmail_category)
await new_text_channel.set_permissions(message.author, send_messages=True)
await new_text_channel.set_permissions(message.author, read_messages=True)
await new_text_channel.set_permissions(message.author, read_message_history=True)
await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
except Exception as e:
print(e)
return
await message.author.send(f"You already have a ticket open! <#{author_modmail_channel.id}>")
your last set_permissions is overwriting all the previous ones lol
figured
you could've done it like so
set_permissions(...., read_messages=True, send_messages = True, ...)
but it was setting them all yesterday
yesterday isn't today
you can do insanely sexy shit btw
overwrites = {
message.author: discord.PermissionOverwrite(
read_messages=False,
send_messages=False,
),
Role1: discord.PermissionOverwrite(
read_messages=True,
send_messages=True,
)
}
... create_text_channel(......, overwrites=overwrites)```
get it? that's an all-in-one
i got it to work with this
that Role1 is just an example of how you could add more than 1 user / role/ whatever
but yea i do get what you're saying
wouldn't suggest that, you want best-practice
no, but smart people do the hours in your case lol
How do I handle if the internet went offline while the task was running?
your bot would crash 🤷♂️
What is the solution for this?
Not quite
discord.py handles it for you
That's one of the main points of the tasks extensions, is to handle cases like these
that's some process management, where you could restart the bot when it has unexpected errors
mb
I wouldn't think about that, just have a decent host
@potent spear that seems to work thanks for all your help 🙂
@sick birch @potent spear So it's not recommended to use try-except block around the entire code block at all?
Don't, for your own sake
lastly, if you want, you could use
modmail_category.create_text_channel(...)
instead of
guild.create_text_channel( ..., category = modmail_category)
but that's up to you
Hi doggo
Don't see you much 'round these parts
definitely no
Bro I love discord.py
Hola birdo
I'm exploring new territory
I would return
Non terrae plus ultra
Okay, thanks that would be better 😁
Getting elo rating for Rapierknight3
Getting elo rating for Miraa Opast
[2023-01-13 02:30:04] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 44c54ee8c27fccf6346343bce5ad02b9e4.
Getting elo rating for Toukah
[2023-01-13 02:30:19] [INFO ] discord.gateway: Shard ID None has successfully RESUMED session 44c54ee8c27fccf6346343bce5ad02b9e4.
Getting elo rating for VivyFluoriteEyes
Getting elo rating for msxuctae```
yeah, why would i have em off
could be that you forgot...
code seems right though 🤔
they are on
have you moved on_ready etc as mentioned?
Hmh I can't install the package. any idea?
[01:40] [server.beerhunter ~] # pip3 install discord.ext.tasks
ERROR: Could not find a version that satisfies the requirement discord.ext.tasks
ERROR: No matching distribution found for discord.ext.tasks```
.ext.tasks is a submodule from discord module from discord.py
that should just come with discord
I hate you

!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
my honest reaction
doggy
Are you cheating on me!? 
no sir i would never
I expected better from you robin
Robin is acting too sus these days
robin amongus
mogus
could anyone help with this code?
its for
so it basically looks like this
its going to be used to sign people like “You have been signed by” the authors role that preformed the command
so basically give the role to the person that was signed
@sick birch
@slate swan
Please don't ping random people
sorry
Are you looking to just give the user a role?
yep
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
also send a embed at the same time
your very smart
but
the thing is i just the want the user to get any specific role it has to be the authors role
The author has many roles, which one?
or do you mean only get the role if the author also has it?
hmm it would just be smart to put a string to make the author pick a role for the member
yo new to python and discord bots
welcome to the hole of "its probably really easy but idk"
lol
@sick birch do you know how i can add another option where its a role option like it would say “role” because the other would pick a role for the member to get roled
like the member part
Yeah just typehint to discord.Role
async def sign(interaction: discord.Interaction, member: discord.Member) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in member.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."
await interaction.response.send_message(msg)```
@sick birch so like where in this coding would i put a "discord.Role"
so it would be like "member: discord.Member, role: discord.Role"
yeah
lol
bots are sentient now
hi, does anyone know how to get user id from when they react to a message
@bot.event
async def on_raw_reaction_add(reaction: discord.Reaction):
if reaction.emoji.name == '👍':
print('hi')
@bot.event
async def on_raw_reaction_remove(reaction: discord.Reaction):
if reaction.emoji.name == '👍':
print('hi')
@sick birch i have a huge problem ```@client.tree.command(name="sign", description="Where athletic directors & head coaches sign players")
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"
if 854573259030921256 not in [role.id for role in member.roles]:
msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
msg = f"Hey {member.mention}! You cannot sign yourself."
await interaction.response.send_message(msg)``` so theres a big problem like where i did the author had to have a certain role to preform the command and it gave a error like "you dont have the role to preform this command" that worked and all but now it does that if the member dosnt have the role that is used to preform the command which is what i dont want
@sick birch
on_raw_Reaction_add doesn't have a reaction parameter
yea i realised now its just payload
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
do you mind helping me?
you can get the user from it
yea
sure, let me read the issue
thanks man
instead of member.roles use interaction.user.roles
alright
@bot.command()
async def alert(ctx, amt, time, *text):
print(amt)
for i in amt:
print(i)
text2 = " ".join(text)
await ctx.send("{}".format(text2))
time.sleep(time)```
let me test
This sends the message once and then never again
amt is a string unless you convert it
would amt:int work
sure. but you can't iterate over an int directly. use range
ahhh I see
also you should use asyncio.sleep instead of time.sleep
and make sure that you wait a minimum of 5 seconds before sending the next message, or you'll get ratelimited
!alert 10000000 0 amongus
Alright
I did do that once and it gave me an error I don't remember it
perhaps you forgot to await it
wait but i dont have “member.roles”
