#discord-bots
1 messages ยท Page 114 of 1
i saw a connection to db.db in the function 
oh ye
but it was told to me I always need to open them and close inside commands etc
for security purposes
enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.
```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
``` Equivalent to...
also just create a pool enable auto commit to save a few lines of code
any help?
how could I do that?
just a sec lemme check docs i have used asyncpg and aiomysql not sure abt aiosqlite lemme check
yeah i don't think there is a pool for aiosqlite u can use a context manager https://stackoverflow.com/questions/53908615/reusing-aiosqlite-connection
too less context to find out
I'm not getting
send more code 
ok
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command(name="ping")
async def test_msg(ctx):
await ctx.send("pong")
bot.run(os.getenv("TOKEN"))
btw this line
await con.execute("UPDATE character_items SET item_quantity = item_quantity - ? WHERE item_ID = ? AND character_ID = ?",(int(quantity_item[a][a] * int(self.quantity.value[0])),quantity_item[a][a+1],interaction.user.id,))```
is not commiting for some reason the values that its sending is 10,5,id
all matches on db but still doesn't update 
are the intents in ur dev portal enabled?
yup!
This one is perfectly working```
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello!')
or change event to listen
u have an error handler?
is this inside some view? and did u use start method to start the bot with no logger setup?
definitely some error
add it in a try except and print
and setup a logger
coz on_command_error dosent catch interaction errors iirc
now commands is working but message aren't
did you add () at the end of listen?
can u show me ur on message event
for i in quantity_item:
try:
await con.execute("UPDATE character_items SET item_quantity = item_quantity - ? WHERE item_ID = ? AND character_ID = ?",(quantity_item[a][a] * int(self.quantity.value[0]),quantity_item[a][a+1],interaction.user.id,))
await con.execute("INSERT INTO character_items (character_id,item_ID,item_quantity) VALUES (?,?,?) ON CONFLICT (character_ID,item_ID) DO UPDATE SET item_quantity = item_quantity + ?",(interaction.user.id,quantity_item[a][a+1],int(quantity_item[a][a]) * int(self.quantity.value[0]),int(quantity_item[a][a]) * int(self.quantity.value[0]),))
await con.commit()
except:
raise Exception("An error occured while crafting!")
I did this try catch rq and still no error
except Exception as e:
print(e)
it's working
๐
still nothing 
check ur db again
or use some arbitrary values instead to check
then its not committing
imma put a checker under commit to check if it reaches tehre
it did 
found problem
its second query
it does not raise error prob bcs it has ON Conflict
fair enough
now trynna find the problem anyways tysm asher 
๐
are u sure ur column names are correct? character_id and character_ID
mhm I found problem, a wrong value was being passed so it was not doing anything
๐
if u put the actual question before a request for help u would have a better chance i suppose
gotta reset your token now
open ur discord go to applications page
yes np
open ur bot
i just cretaed it for the screen
go to bot settings page
and next
yep
alr done
well there you go your bots online
rand_colors = ["0x"+''.join([random.choice('ABCDEF0123456789') for i in range(6)])]
await role.edit(colour=rand_colors[0])
Error:
payload['color'] = colour.value AttributeError: 'str' object has no attribute 'value'
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").
There is an alias for this called Color...
British people be like
huh?
!d discord.Colour.random @bright wedge
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
There's a built in random method for you
oh
anyone got any good leader board image template?
how much slots
thank you!
nice but are these under mit or cc license 
free license
oh fine then thanks
Is it possible to make the bot answer a hello without the person having put an prefix in front of it?
yes, on_message event
ill look in the documentation
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
Are you using pycord?
First step is to figure out what you're using
This doesn't show anything
wdym what im using
pycord 90% sure
What library did you use as you were coding the bot?
i think its cloned from a git repo
Pycord.. discordpy... disnake..?
i bought the bot but they was using visual studio to code it all
No wonder it looks terribly written
No offense I mean
nah the guy who i bought it from like it works for him but not for me
Generally buying discord bots are scams
^^
thats the line thats erord
But the cause of the issue is probably a pycord and discord.py conflicting install
first of all u need to figure out what module is being used second if u have the module installed in your env
Not sure why the person making the bot decided to use a subpar library like pycord.. but it's there
i mean i never knew people were ready to pay for bots ๐
i dont understand how u expect ppl who have no coding knowledge or time to learn to get their own bots and people definitely are not going to use their time for free to make them for them
true
That's why bots like MEE6 or rhythm exist
Well not rhythm I guess
< insert popular discord bot here >
wdym? those bots only do specific things
They're meant to be general purpose
In fact YAGPDB stands for "yet another general purpose discord bot"
to a certain extent yes
The only reason I can think of people paying for their bots is to have it custom tailored to a very specific usecase
For all else you have your generic popular discord bot
how can i check if the author is in a tempchannel already if they try to override the tempchannel settings with a vc which is already a tempchannel
is it necessary i commit the channel id and all in db, coz i dont really want to do that
depending on how long the temp channel lasts you could store the id in memory or have a naming convention in discord that identifies the channel
its not that i am against buying or selling but thing is whatever u are buying or selling from uknown sources some pre requisite knowledge is necessary otherwise u have literally no idea what u are even buying
no help with nukebots here
if it was a nukebot, discord wouldnt verify it would it
just the name is nukebot, it doesnt really nuke servers
which there are more people out there like this than you would realize
ig both of the options are a no
coz the tempchannel might last due to user's choice, and idk if any method exists in pycord to check if its a tempchannel or not
well yea thats common sense, its your money your spending. I've "stolen" customers from people just because the other person had no clue wtf they were doing lmao
wdym by temp channel?
i dont think discord has any sort of temp channel but they do have threads which you can use like one other then that you need a way to identify them
a temporary voice channel which will be deleted once the user leaves that channel
yea i was about to say there is no such thing as a temp channel w discord api
that would be fine, but i need to check if the author is in a temporary voice channel, and i have no idea how you do that without comitting it to db, since that seems like a lot of work
or when they create a temp channel, name it their user and when they go to create another check for the channel they are connected too and if it matches their user then boom
oh yess, you are a genius tysm
hello, I need help with a command.
let's say I create a recipe command I create a list of recipes 'pasta', 'cake' and with my bot discord when the order I give the recipe of the dish requested for example I want the recipe of the cake I do >recipe cake and it gives me the ingredients of the recipe and the same for >pasta but with the ingredients of the pasta and not the cake
use sub cmds
what does it means
you could store the ingredients as a bitmask then the recipe by using bitwise or then you can check using and
thats going into more general python tho then library
I don't understand can you redirect me to the documentation or a video?
https://codeforces.com/blog/entry/18169 here is some general background on bitmasks
just use an api for data
lmao that is a little bit too much for something as simple as what he is trying to do
well they can ask for help in the normal help channels if they are confused
Why this when u can just use dictionary
more efficient both on memory and processing
you could but then you would be repeating ingredients per recipe
its also more concise and easier to understand with bitmask
at least code wise not the result without processing
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.
@bot.command()
async def mute(ctx, member: discord.Member, muted : time = None, *, reason=None):
muted = discord.utils.get(ctx.guild.roles, id=1019274735516909578)
time = humanfriendly.parse_timespan(time)
member = ctx.author.mention
if member == None:
await ctx.send("Please please mention a member you want to mute")
elif time == None:
await ctx.send("Please mention the time you want the member to be muted!")
elif reason == None:
reason = "None"
else:
await member.add_roles(muted)
await member.up
await ctx.send(f"{member.mention} was muted by {ctx.author.mention} for: {reason}")```
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Among Us IL Bot\main.py", line 120, in on_message_edit
async def mute(ctx, member:discord.Member, time, *, reason):
AttributeError: module 'datetime' has no attribute 'now'
PS C:\Users\PC\Desktop\Among Us IL Bot> py main.py
2022-10-25 21:43:18 INFO discord.client logging in using static token
Among Us IL is online!
Synced 0 command(s)
2022-10-25 21:43:20 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 4bf55f17b43eed189d19fe473d2764b8).
2022-10-25 21:43:29 ERROR discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1214, in _actual_conversion
return converter(argument)
TypeError: time.time() takes no arguments (1 given)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Among Us IL Bot\main.py", line 361, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 978, in invoke
await self.prepare(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 895, in prepare
await self._parse_arguments(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 802, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 672, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1323, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1223, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
discord.ext.commands.errors.BadArgument: Converting to "time" failed for parameter "muted".```
why are you typehinting muted to time? What is time?
Getting philosophical?
haha out of context python is very philosophical
Hi, is it better a task loop with a minute delay or a while loop with an asyncio.sleep(60)?
task loop will give you the builtin control features such as being able to stop it and stuff
okay ^^ ty
Also reconnect logic is handled for you
hello I am looking for how to do so that when my bot sends a message, I answer it, and I would like my bot to be able to retrieve my response
Good Morning
i have returned to ask more cringe/noob help with python on my discord bot that was running perfectly fine and now something happend and its dead
this is a DB error
Hi id like to know how do I make the bot's errors that appear in the terminal to be sent to a discord channel of choice
I swapped my postgres from heruko to sudo
but both kept giving me same error
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
Thank you.
Hmm did i do this right? because errors that occur in the terminal isnt appearing in the channel
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
channel = self.bot.get_channel(removedid)
await discord.ext.commands.on_command_error(ctx, error, channel)
embed=discord.Embed(title="Error",
description=f"{error}",
color=discord.Color.orange())
await ctx.send(embed=embed)```
no need for await discord.ext.commands.on_command_error(ctx, error, channel) and the useless f-string description=f"{error}",, your function can also cause recursion i think, did you load the cog, which errors?
cog loaded
errors for eg this
line 32, in CheckLvlUP
for i in row:
TypeError: 'NoneType' object is not iterable```
left that error on purpose for the sake of testing this
and where do you get these errors exactly?
What is row?
thing is i want to show the errors because the bot is hosted in a virtual machine and i cannot always be there to check on the console, thus i want it to be sent in a specific channel
Well, on_command_error can only catch errors from context based commands
why is my discord bot sending 5x the amount that its suppost to
and it runs when i dont have any terminals open
If anyone has some time to look at this id be grateful
https://hastebin.com/iqafamulos.py
[AttributeError: type object 'Client' has no attribute 'slash_command']
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Do I only need one of these to get commands working?
bot = commands.Bot(command_prefix="!", intents=intents)```
oh I guess I only need commands and not client.
remove client
its discord.Client()
and its deprecated dont use it
wo ur tag
anyone know why, when I do emoji = await bot.wait_for("message", check=check, timeout=60) it's coming back as \ud83e\udee7 and how can I get it to save as :bubbles:
not sure what unicode characters \ud83e\udee7 represent, but the ๐ซง emoji would look like \U0001fae7
^
When I reply with ๐ซง it comes out as that weird unicode...
is there a proper way to have a wait for message get :bubbles: ?
i dont get the same results
standard emoji in discord are represented with unicode emoji, and discord uses their own names so there isnt an easy way to exactly match what discord shows for the emoji all the time
you can either find some name mapping discord uses if that exists, create your own, or use something close enough like the builtin module unicodedata to get the emoji's name
!e py import unicodedata emoji = '\U0001fae7' print(unicodedata.name(emoji))
@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.
BUBBLES
discord.EmojiConverter might work, don't quote me on it though
nah thats for custom emoji only, PartialEmojiConverter too (annoyingly)
i had to use a pypi package like emoji and a custom converter to check if a character(s) was standard emoji
hmm emoji actually has its own localizations, but it doesnt seem to match the ones in discord (at least for one emoji that i checked)
works with twemoji_parser
async def addrole(ctx):
await ctx.send("What is the role name?")
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
msg = await bot.wait_for('message', check=check, timeout=60)
role_name = msg.content
await ctx.send("What is the emoji?")
msg = await bot.wait_for('message', check=check, timeout=60)
emoji = msg.content
await ctx.send("What is the description?")
msg = await bot.wait_for('message', check=check, timeout=60)
description = msg.content
## check if role_name is a valid string
if not isinstance(role_name, str):
await ctx.send("Role name must be a string.")
return
## check if role_name is already in use
with open(configFileLocation, "r") as configFile:
configData = json.load(configFile)
roles = configData["roles"]
for role in roles:
if role == role_name:
await ctx.send("Role name is already in use.")
return
## check if emoji is a valid string
if not isinstance(emoji, str):
await ctx.send("Emoji must be a string.")
return
## check if description is a valid string
if not isinstance(description, str):
await ctx.send("Description must be a string.")
return
## append to roles array in config/config.json
with open(configFileLocation, "r") as configFile:
configData = json.load(configFile)
roles = configData["roles"]
roles.append({
"react": emoji,
"react_id": 0,
"role": role_name,
"description": description,
"role_id": 0
})
with open(configFileLocation, "w") as configFile:
json.dump(configData, configFile, indent=4)
await ctx.send("Role added.")
await role_system()```
This is the code I'm using right now :/ still getting weird input into my json
``` {
"react": "\ud83e\udee7",
"react_id": 0,
"role": "water_buddies",
"description": "15 Min drink reminder",
"role_id": 1034626366181748866
}```
async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable
i keep getting that in error
Traceback (most recent call last):
File "C:\Users\Nathan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 70, in button
button_views = red_button()
File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 20, in __init__
async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable
full error
You can create a subclass with discord.ui.Button (class MyButton(discord.ui.Button)) or as shown in your example you need to use discord.ui.button
can you show the code for your view? the lines dont make sense in your traceback which likely means the bot is running an older script than what's been saved
(as i will find out below, that is the expected traceback which doesnt show the decorator that had the actual error)
im getting new error
Traceback (most recent call last):
File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 16, in <module>
class red_button(discord.ui.View):
File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 21, in red_button
async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable
code
class red_button(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
@discord.ui.Button(label="Press", style=discord.ButtonStyle.red)
async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
await interaction.response.send_message("You pressed button")
oh you made a typo in your decorator
@discord.ui.button is the correct name, lowercase b
class PurgeView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
async def button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
mycursor.execute(f"DROP TABLE `{interaction.guild.id}`")
mycursor.execute(f"DROP TABLE {interaction.guild.id}_custom")
mycursor.execute(f"DROP TABLE {interaction.guild.id}_blox")
await interaction.response.send_message("Devil Fruit Tables successfully deleted")
log = f"Deleted Devil Fruit Jornal from {interaction.guild.id} ({interaction.guild.name})"
write_log(log)
how do i make it so this button only works for the person who sent the command?
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
what does the slash mean
It means interaction is positional only
In discordpy to create an embed you just create it in the command itself or wherever you want embed = discord.Embed, is there an equivalent for modals?
#delete invite links
@bot.event
async def on_message(message):
if message.guild is None:
return
discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
modrole=937402417069293589
if discordInviteFilter.match(message.content) and modrole not in message.author.roles:
await message.delete()
await bot.process_commands(message)
this code deletes messages if they are an invite link, but it wont delete messages if it contains text + invite link. how can i change it so that if an invite link is any part of a message, it will delete it?
https://discord.gg/ <- in message.content
@austere vale Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
@bot.event
async def on_message(message):
if message.guild is None:
return
modrole=937402417069293589
invitestring='dscord.gg/'
if invitestring in message.content and modrole not in message.author.roles:
await message.delete()
await bot.process_commands(message)```
this works but if i (a mod) send out an invite link, it still deletes it. any idea why it might be passing the modrole check?
(also i purposefully misspelled the invitestring link so the bot doesnt delete the message)
my intents are `intents=nextcord.Intents.all())`
this is how you define the role
@bright wedge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
that fixed it. thank you!
you are welcome!
Hi
hello I am looking for how to do so that when my bot sends a message, I answer it, and I would like my bot to be able to retrieve my response
!d discord.ext.commands.Bot.wait_for there are some examples if you open the doc
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
thanks
global check in disnake for slash_commands?
how can i update a button on click?
i cant send what im trying to say but .gg isnt only way for invite to be made
this bot keeps deleting my message
yes you can do it in callback
like invite/vanity
thats why his way of using re is better
hi, you typed modrole=message.guild.get_role(937402417069293589) right? sorry i accidentally deleted my code
i tried to install slash commands bit it failed
Are you watching a tutorial?
Probably lmao
how can i see what version of dpyy i have ?
yes
pip show discord.py
Stop, it's outdated
?
..
I told you to do something, and you did a different thing.
i have 2.0.1
good, then
then what
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Follow this guide instead of the tutorial you had
need i to install the new dpy version?
You are on the latest already
I read the GitHub but to do slash command it's not with
@slash.slash(name="name")
``` ?
as I said, stop following that tutorial
yes but i dont understand whati havez to do now
it doesnt explain howto installslash commands
Yes
thank youu
but if i use that, i get this:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kouxi\Runa\main.py", line 91, in on_message
if discordInviteFilter in message.content and modrole not in message.author.roles:
TypeError: 'in <string>' requires string as left operand, not re.Pattern
@bot.event
async def on_message(message):
if message.guild is None:
return
modrole=message.guild.get_role(937402417069293589)
discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
if discordInviteFilter in message.content and modrole not in message.author.roles:
await message.delete()
await bot.process_commands(message)
thats not how you use a regular expression
you probably want discordInviteFilter.search(<string>)
`26.10 06:11:25 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
26.10 06:11:25 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
I have a bot that sends welcome message with an image wheneever a user joins, can this be the reason why my bot is being ratelimited>
The server is very popular on where this bot is
Do you have any logs/warnings about where this is coming from
Maybe before the actual error
26.10 04:15:31 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
26.10 04:28:26 [Bot] Ignoring exception in on_member_join
26.10 04:28:26 [Bot] Traceback (most recent call last):
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/client.py", line 612, in _run_event
26.10 04:28:26 [Bot] await coro(*args, **kwargs)
26.10 04:28:26 [Bot] File "/cogs/listeners.py", line 77, in on_member_join
26.10 04:28:26 [Bot] await channel.send(f"Hey {member.mention}, welcome to **{member.guild.name}**",file=disnake.File(welcome_file_path))
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/abc.py", line 1523, in send
26.10 04:28:26 [Bot] data = await state.http.send_files(
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/http.py", line 401, in request
26.10 04:28:26 [Bot] raise HTTPException(response, data)
26.10 04:28:26 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
its just a repeat of this over
For popular bots, is there a timer for the welcome message for a user?
Im assuming it's because too many users joined at once
you could just not do it and let discord do welcomes
I don't think anyone cares anwyay
figure out why you're trying to convert '%mention tach' to int
It sends a custom image of the user's profile picture along with custom text with the welcome message
it's for a client haha not for me to say
Can I ask how often these are being sent
Your lib should be automatically slowing down
you need to do some real messed up stuff to get 429s
Im using disnake
And not sure. it depends of course on how often user's join so its variable
lmao
I guess you could make a queue of messages to send
Then send one like every few seconds inside a tasks.loop
Yeah I was thinking of that.
mind giving me a doc link to that?
Deferring just says "I acknowledge this interaction, I'll followup later"
it should be interaction.response.send_message
defer doesn't have any arguments
No, defer then followup in this case
Yes-
defer then send a follow-up
Then send it when you want to
You have 15 mins
what error
Are you hosting on repl it by any chance
Nope, pebblehost
Im hosting from my computer atm and it is working. but this has happened twice now
Looks like it's on the bad hosts list on the dpy server, why are you using that instead of a vps
Im now adding a 1s timer to the message
Never had any issues with pebblehost so far until this
Thats why never went to a vps
its cheap and was easy to setup for my clients
yeah that's the thing with bad hosts
It's good until you really need it to do something
But having a bad server/host lead to a 429 ratelimit?
How does it stop dpy from automatically stopping the message spam
idk bad network management ig
yeah weird
How cheap
$3 per month
VPS on galaxygate costs the same yet provides more functionality
@unkempt canyon
yes

Multiple commands isn't working ```
from email import message
import os
from dotenv import load_dotenv
import discord
from discord.ext import commands
load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_connect():
print(f'I am awaken {bot.user}')
@bot.event
async def on_message(message):
if message.author == bot.user:
await bot.process_commands(message)
if message.content.startswith('hello'):
await message.channel.send('Hello!')
@bot.command(name="ping")
async def test_msg(ctx):
await ctx.send("pong")
@bot.command(name="quote")
async def test_quote(ctx):
await ctx.send("quote")
bot.run(os.getenv("TOKEN"))
you're only processing commands if the bot is the message author? why?
ok so what to do?
I'm asking you why you're doing that
do you understand what this code does
got my fault . Any way to process commands?
...
I don't know how to explain this
this checks if the message author is the bot
so you're only processing commands if the author is the bot
is it okay?```
if message.author == bot.user:
return
but i want to process my commands
yup!
sure, and where will you process commands
you can process it after the if statement
that's what i am asking to u?
will it work๐ค
how would i go about ending a specific instance of a class?
@vocal snow great it's working
wdym "ending"
if someone quits a session of my game, im doing 2-3 things. 1 is making their text channel invisible except to admins (for review purposes)
secondly i want to break their current game instance so it resets the game stats
usually i do that by either restarting bot or by deleting the channel
without deleting the channel tho idk how to break the players current game instance
oh and third is renaming the channel
why is it showing me error?```
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001B534007160>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed
Explain the logic you implemented
I would keep the game data inside the command and bring the host's ID into global list (I don't mean global var)
as long as the function is exited the garbage collector frees up the allocated memory
by function i mean scope this instance is present in
Does the game have an api
is there an implementation of decorator where u can set cooldown for command to a specific role
also currently my bots are like this
class MyCogStaff(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot = bot
@app_commands.command(name="ping")
async def ping(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("pong", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCogStaff(bot))
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
async def main():
for _folder in os.listdir("./commands/staff/"):
for _file in os.listdir(f"./commands/staff/{_folder}"):
if _file.endswith(".py"):
await bot.load_extension(f"commands.staff.{_folder}.{_file[:-3]}")
async with bot:
await bot.start(config.token)
if __name__ == "__main__":
asyncio.run(main())
How can I
- Get the slash commands to show on discord when I type the slash
/ - Set StaffCog commands to show only to members with staff-role
- you need to sync your app commands to discord, usually done in a setup_hook or a prefix command like so: ```py
@bot.event
async def setup_hook():Synchronizes global commands:
await bot.tree.sync()or for a specific guild via ID:
await bot.tree.sync(guild=discord.Object(267624335836053506))``` 2. discord doesnt allow you to do this from the bot directly, i.e. an admin has to configure the slash command in Server Settings > Integrations to specify which roles are allowed (the closest thing you could do would be using the@app_commands.default_permissions()decorator to limit visibility based on permissions)
how to send a private message with the py slash commands of discord?
get the user from the interaction and use their send() method
how get user ?
!d discord.Interaction.user
The user or member that sent the interaction.
for example: py @bot.tree.command() async def my_command(interaction: discord.Interaction): # Respond to the interaction (always required in some form) await interaction.response.send_message('Hello in this channel!') # DM the user await interaction.user.send('Hello in your DM!')
as usual you might get a discord.Forbidden error if the user has their DMs closed
Isn't it in ext
whaT?
Anyone know I can make my bot automatically send a message once a certain amount of messages are sent in my general chat by users
Yea count them in on_message ig
Explain further
Visual
Are you installing them through vsc's embedded terminal
no
Do that
Is there only one interpreter installed on your machine and are you using venv
Hey random question: is it possible to have a bot do prefix commands and slash commands? I'm having an issue where I enabled a basic slash command but now the previous prefixed commands do not work (the bot does not respond). I'm using nextcord and I'm fairly certain I have all of the scopes / intents enabled for both
To my knowledge, discord.py supports hybrid commands, not sure about nextcord
Tbh they only differ by decorators
And the type of ctx can either be Context or Interaction, depending on how the command was called
Right
I can get a basic "echo" slash command, but my previous ~ping command is no longer picked up by the bot
i havent heard that happening before, but there's a lot of things that could go wrong for prefix commands to not work
why is it showing me error?```
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001B534007160>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed
thats a bug with asyncio, you can usually ignore it
In nextcord anything can go wrong
I see I see
got it
e.g. missing the messages intent, on_message not processing commands, missing the message_content intent, and if its in a cog the command could be shadowed by another function
@velvet compass the last point wouldnt be the case right? does your prefix and slash command have different function names?
They do have different names
Have you loaded the cog?
Here are the cogs that get loaded:
is there an implementation of decorator where u can set cooldown for command to a specific role
Hey Brad! Fancy seeing you here
!d discord.ext.commands.BucketType.role
And here is where I set up the bot:
# some stuff above
intents = nextcord.Intents.default()
intents.message_content = True
class Bradbot(commands.Bot):
"""
Bradbot core.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = "Bradbot"
self.dev_log = int(DEV_LOG)
def add_cog(self, cog: commands.Cog) -> None:
"""
Delegate to super to register `cog`.
This only serves to make the info log, so that extensions don't have to.
"""
super().add_cog(cog)
logger.info(f"Cog loaded: {cog.qualified_name}")
bot = Bradbot(command_prefix="~", intents=intents)
#more stuff below
The role bucket operates on a per-role basis.
New in version 1.3.
I also don't think prefix commands and slash commands should interfere unless you've set them up as hybrids?
(a lot of this is heavily inspired from @lament depot )
They should be completely separate
Can you show both of the commands?
have you configured them as hybrids?
Theyre 2 separate comamnds
I am now wondering though, should I modify the prefix commands where I initialize them?
^
I'm guess not then
@ocean dragon what do you mean by "a specific role"? do you want the cooldown to only apply to that role? there's several different ways to design it with dpy 2.0
So some code blocks:
Ping command (prefix)
from loguru import logger
from nextcord import Embed
from nextcord.ext import commands
class Ping(commands.Cog):
"Send an embed about the bot's ping."
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="ping")
async def ping(self, ctx: commands.Context) -> None:
"""Ping the bot to see its latency and state."""
logger.debug(f"Command `{ctx.invoked_with}` used by {ctx.author}.")
embed = Embed(
title=":ping_pong: Pong!",
description=f"Gateway Latency: {round(self.bot.latency * 1000)}ms",
)
await ctx.send(embed=embed)
def setup(bot: commands.Bot) -> None:
"""Load the Ping cog."""
bot.add_cog(Ping(bot))
New slash "echo" command:
from nextcord import slash_command, Interaction
from nextcord.ext import commands
class SlashTester(commands.Cog):
"""Testing slash command implementation."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@slash_command(guild_ids=[redacted], description="Echo command")
async def slash_echo(self, interaction: Interaction, arg: str):
"""Testing a slash echo command"""
await interaction.response.send_message(f"{arg}")
def setup(bot: commands.Bot) -> None:
"""Load the SlashTester cog."""
bot.add_cog(SlashTester(bot))
actually I mispoke, I want limits for commands to users that do not have a "membership" role
ah, so that would require a dynamic cooldown
what library and version are you using? discord.py 2.0 comes with @dynamic_cooldown()
and so does nextcord and disnake
do you have an on_message event by any chance?
I do not
pip show discord.py to check the version
https://github.com/nextcord/nextcord/blob/master/examples/application_commands/cog_example.py#L19 have you tried this method?
2.0.1
examples/application_commands/cog_example.py line 19
@nextcord.message_command(guild_ids=[TESTING_GUILD_ID])```
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
the context menu app commands?
wut
thats what you linked
Is the logger getting triggered?
negative
is message content intent enabled in the dev portal?
Do you only have 2 commands?
Yup:
I have 1 slash command in its own cog, and I have 5 prefix commands in their own cogs
Do the other prefix commands work?
Nope, none of them are. (and it isn't getting logged either)
@ocean dragon the BucketType can be whatever you want, but for changing the cooldown you can pass a function that returns a Cooldown only if the user doesnt have your membership role, for example: ```py
def cooldown_callback(ctx):
if <user has membership role>:
return None
return app_commands.Cooldown(1, 10) # 1/10s
@bot.command()
@commands.dynamic_cooldown(cooldown_callback, commands.BucketType.member)
async def my_command(ctx):
...```
I added a log message to the slash command, and that is getting logged
you sure your bot is not possessed by some Halloween ghost?
neat, thx
That would be a spooky danger doot pumpkin skeleton bat if it is
have you tried reloading the cog of each command after the slash command gets setup?
And the context commands work if the SlashTester cog isnt loaded?
I need to call a async fuction on __init__ but I can't sync its not async. So my question is how can I make __init__ async?
You can use a classmethod
I commented out the setup for the slash command and still no dice. Could be a massive lag in enabling message intents from discord's side?
hm nextcord's source is a bit odd, they chose to introduce the concept of cogs to discord.Client in order to implement slash commands inside them
have you tried using a listener to see if you're receiving MESSAGE_CREATEs events?
I haven't, worth a shot
because you forgot it in your constructor(__init__())
In this case it would be bot so add another argument
you forgot self in the parameters of the constructor
No worries๐
I tried this in the Ping cog class, no luck:
@commands.Cog.listener()
async def on_message(self, message):
print(message)
I'm going to chalk it up to a lag on the perms being set up on discord's side. Will come back to this later
don't sync globally
Have you tried using nextcords logger?
i'm pretty sure it shows what events get received
Hey,
I'm trying to make my slash command into an prefix command.
Here is my code:
@bot.command()
async def activity(ctx, str):
activity: discord.Option(str,"Change the bot activity",required=True):
if not isAdmin(ctx):
embed = discord.Embed( description="Access Denied: You are not an admin.",
color=0x3dad5b)
return await ctx.send(embed=embed)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{activity}"))
embed = discord.Embed(description=f"Bot activity changed to {activity}",
color=0x3dad5b)
await ctx.send(embed=embed)
I'm trying to make it into $. Right now, I have troubles with the option.
It's not indented in the class!
what's the issue? any tracebacks?
I have this error, i believe.
!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.
ah, there we go
What does that do?
@slate swan take a look at the guild kwarg ^
Because theyre in the class and cant access an instance
Cant you just use commands to setup the app commands?
you should be able to solve syntax errors by yourself...?
Nope.
actually i think its app_commands
can I create a custom decorator using default_permissions so I can actually hide the commands from those who do not have a role?
(I'm bad at decorators) :D
well then it's commands
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_cog.py at master ยท Pycord-Development/pycord
you can't toggle slash commands by roles, only permissions
ok
Update: I had to give my bot a server role with higher perms
why exactly?
I have no idea, but it worked after that
๐ค
Guys, any good vps servers that are good for discord bots that are around $10 a month?
or $15, pricing isnt really an issue
It's for a server with 5k+ people
I've tried pebblehost but it buckled under load
Your bot was possessed indeed
kinda off topic but does anyone know any packages which convert seconds into things like "1 minute" if my seconds = 60?
!pypi time-str | something like this?
You can also use regex
How do i get all channels in the SlashOption
how do i check if a user has a role in a completely different server
??
guild = bot.get_guild(completely_different_guild_id)
user = guild.get_member(user_id)
role = guild.get_role(role_id)
if role in user.roles:
#user has the role
else:
#user does not have the role```
Is there a way to do if interaction.custom_id == "..." but in modal class?
can someone explain to me what exactly the benefits are if switching from autosharded client to "horizontallly sharding" or "traditional sharding"?
do you know if theres other ways besides that? because if its just dscord.com and dscord.gg, i can just have it check those 2 strings
autoshard just does it for u
?
someone else already answered u
where ?
Hi guys!
server.unban(user)
Will this work, if the user is a string with a valid user ID. and the server is a string with a valid guild ID?
no
is there a correct way to write it?
autosharded doesn't make any sense though? It's running all shards in the same process so if my process goes down, so do all my shards. Whereas vertical and horizontal sharding don't work that way and I want to know how they work
async def unban(self, ctx, user: nextcord.User):
await ctx.guild.unban(user)
https://paste.pythondiscord.com/uluropifev so
i'm making a currency bot
and a crash command
and in the paste on line 47
the removed_players dict doesn't update the command
on line 5, i print removed_players and this is a screenshot from my console even after i used the CashOut view
I have that as my unban command
Hello
i dont think server.unban is the same as await ctx.guild.unban
yeah
autoshard isn't a multiprocess thing lol
ctx: nextcord.Interaction ?
I need a way to manually specify a server and user then unban
use inter: nextcord.Interaction
I know it isn't. It's running through the same process that my code is so if that process goes down, so do all my shards.
will Bot.fetch_user(id) get me a user object?
Yes but ctx also requires
he is using interactions dude lol
ctx is ctx interaction is interaction
Correct
Fair
Inter is better in this situation tho
could anyone help me please?
so does anyone know a way I can unban someone on a specified server?
I don't want CTX as it's a predefined server ID
just pass guild: int as a parameter
i dont see why there needs to be a new view created every time you're updating the message - have you considered editing the message the view is attached to inside the cashout() callback?
Sorry i'm a bit of a noob
where do I pass it in?
actually youll also have to use large int
that doesn't make sense?
not in python no
Did the ID go up a digit or?
ye
Hm. It should still work, python doesn't have trouble with large integers
async def transfer(self, inter: disnake.ApplicationCommandInteraction, server_id: int = Param(large=True), old_server_id: int = Param(large=True)):
i have to do like this cause if i just pass server_id:int when u input an int if its too large, it won't accept it and let u invoke the cmd
how to print the new messages sent in a specific channel?
@bot.event
async def on_message(message):
msg = message.content
if message.channel.id == 9630752822014022:
await ctx.send(msg)
this might do it
Interesting. I'll have to check it out, thanks!
where do I get the url to install the discord.py version before 2.0?
the one that didn't support slash commands
is it this one?
https://github.com/Rapptz/discord.py/tree/v1.x
just use pip?
!pypi discord.py
I forgot I could just ==version
hello
does anyone know what the issue is here
import discord
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print(f"Logging in as {client.user}...")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == "hello":
await message.channel.send("Hello")
client.run('TOKEN')
this is my error
import discord
client.discord
@client.event
async.client sub How do I fix the bug?
if setA <= setB
if setA true setB false
if setA false setB true
@discord.ui.select(placeholder="Pick Devil Fruit table...", max_values=1, min_values=1, options=options)
async def callback(self, interaction : discord.Interaction, drop : discord.ui.Select):
lengeth = len(drop.values)
self.pick = drop.values[lengeth-1]
do i have to have a interaction with the user everytime they change something in the menu
i want them to be able to pick what they want on the menu then press a button to submit it
apparently the problem is with the first line
can you provide a traceback? seems like an odd error
just realized that the error is unique to Visual studio code
it works on other IDEs such as spyder
but VSC is what i'm using to run my bot
how do i fix the error there
Is this something to be worried about? My bot is taking really long to startup
uhm it could be an environment issue
or it could be something else, that's the reason I wanted the complete error
how can I call an async fuction insdie __init__
Ok yeah, notice how in the traceback it imports the urllib module in your folder rather than the standard library one, hence the error.
oh?
how to i make it such that it imports urllib from the standard library one
does anyone know how to fix this 'clear' is not recognized as an internal or external command, operable program or batch file.
Hello, I can't install discord.py on Python 3.11.
The command: py -3 -m pip install -U discord.py
The Errors: ERROR: Failed building wheel for multidict
just rename your urllib file so it doesn't conflict with other modules
do pip install discord.py or pip install discord
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build frozenlist multidict yarl ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
I tried both
go in terminal and type pip freeze then send a pic of it
alright
attrs==22.1.0 jsonschema==4.16.0 pyproject-toml==0.0.10 pyrsistent==0.18.1 toml==0.10.2
idk WHY TF i have a file named after that in the first place
is pip updated?
How can I check?
@pallid igloopython -m pip install -U pip
Requirement already satisfied
pip install --upgrade pip
same
damn bru
bot token
Dang
error: subprocess-exited-with-error
good luck fixing that last time i tried it didnt work
Seems like an effect of those libraries not currently supporting Python 3.11. They seem to be known issues.
apperently this work
pip install python-dotenv
But im not sure it helped fixed someones but idk
Pretty clear error, check if you are actually providing a correct token.
How do you use python obfusticator
ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
i am
well you likely aren't, given the error
I already installed this libraries
i'll just reupdate the token
or ykw just recopy it
alright yeah that was my fault
thats also if ur self botting error
it wont log u in and it gives u that error
neat
I installedd 3.10 and now it works. Thank you
Hello, how can I make so that as many events as there are that answer me as many times to the orders with the same embed but different information of the events?
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.
Hello!
Ive been trying to figure out how to do this
Can anyone help me?
If you click on the blue it redirects you to a liink
Should I use pycord or discord.py?
pycord in my opinion
its (yourtext)[link]
or the other way around
ty
np
or yourtext
with the () []?
yup
ty
is there a way to make a number increase each time in the output of a for loop? for instance im making a leaderboard command and i did it with for result in results: embed.add_field(name=f'{result[1]}', etc... but id like for each result to have 1), 2), etc for each line
!d enumerate
enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.
```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
``` Equivalent to...
ooo but how would i put that inside of the embed? embed.add_field(enumerate())?
bruh
for i, result in enumerate(results):
embed.add_field(name=f'{i + 1}) {result[1]}',
ohhh ok thanks
xy-problem
The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
For more information and examples, see http://xyproblem.info/
cause I want to call a fuction that touched DB so it has "await"
What is this the init of
and I can't call it on __init__ of a diff fuction since its not async
con = sl.connect('db.db')
cur = con.execute("SELECT items.item_name FROM items INNER JOIN character_items ON items.id = character_items.item_id WHERE character_items.character_id = ? AND items.item_category != 'Weapon' ", (user_ID,))
row = cur.fetchall()
return row```
```class _Unequipitems(discord.ui.Select):
def __init__(self,invoke_interaction) -> None:
self.user = invoke_interaction
items = get_equipped_items(self.user)
....```
this is an example
Use a classmethod
The latter(the message I'm replying to, aka this one)
wdym?
The syntax for hyperlinks in md files is [text](link)!
yea as said I always mix them up
Yep and i was telling you which was the correct one by replying to the message that shows the correct syntax!
I'm not getting any error messages, but I still get "Application did not respond" from the bot
Do you have error handlers
no
anyone?
@orchid bearthe decorator add_command doesnt except any arguments
class MyCog(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self) -> None:
print(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})")
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
print(error)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
added on_command_error, but still doesn't print any errors
Do regex search on_.*error and @.*\.error
You either shouldn't have any error handlers at all or they should raise the error if it wasn't handled by them
hey!
I was wondering how to do something:
I want for when the bot joins a new server it makes there role change to the top of the roles
You can't edit your top role
so I cant have the bot make its own role go to the top?
can a bot add a role to themselves if the role is higher then theres?
No, a bot works same as a user so anything a user can do a bot can do and same with user limitations, bots have lower rate limits though that's only difference, so no they can't that wouldn't be logic
a "workaround" would be to have default perms on the bot set to admin and then you can move the bots role above the highest non admin role
u need to use big int
reason: str = "No Reason" also works
is that bcs of the new conversion limits or just a dpy thing?
its always been a thing
gotcha
do lowercase
param
it might not even be the same for discord hold on
ok so apparently with dpy u have to use a str then convert it to an int lmfao
another reason why i like disnake
this is doable with disnake but not dpy. dpy you need to make it a str then convert to int
pycord same thing
gotta use str then convert to int
javascript doesnt accept that long integer, and so does discord
accepting a string and converting it to int is the only choice here
or use disnake
Hello, When I type in my terminal: pip install discord
The terminal responds with: bash: pip: command not found
So is pip uninstalled or sumn?
disnake does the str to int conversion internally yeah
love the wrapper :p
python -m pip
bash python command not found
try python3.8 / python3.9 or whatever version of python you installed
Maybe pip3?
not found
i'd just suggest installing pip properly with python
download this file and run it using python
pip install discord.py
nvm read that wrong
do you have python installed? if not install python3 and then install python3-pip
can someone give me an example of button persistency in cogs?
Guys any good hosting services?
someone help me with this one please
Is it bad to have multiple scripts with the same bot token?
why not just combine them? @silent portal
cuz Iโm lazy ๐ตโ๐ซ
it's simple dude
Yes.
Use Cogs.
yh right I wanted to, but haven't used them before
Is your code rewrite, and discord.py?
Hm, what all do you have.
lol basically many things
Leaderboard system, for voice and chat
level system and temp voice channels
all that kind of stuff
exactly lmao
wait show me ur current workspace
0-0 im sweating at the thought

just like 500 subprocess command chainlinked starting each part of the bot

keep getting this when I try my bot out. It gives an error on the prefix line:
client = commands.Bot(command_prefix=">")
I get:
File "C:\Users\User\PycharmProjects\pythonProject\main.py", line 6, in <module>
client = commands.Bot(command_prefix=">")
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
It never needed intents before, what's changed and how do i fix it?
A lot
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@bot.event
async def on_message(*, msg, member: discord.Member):
channel = bot.get_channel(996119147337494538)
embed = discord.Embed(title=f"New feedback! \n \n User: {member.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(icon=member.display_avatar.url)
embed.set_footer(text=f"Requested by {member.name} | {member.guild.name}")
await channel.send(embed=embed)
await embed.add_reaction('')```
[2022-10-27 16:28:39] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() takes 0 positional arguments but 1 was given
Not discord bots related question
ewww don't get the channel in the event
What for did you even put the *
but i wanna do like if a member sends in a spesific channel
cuz if they will do " " too it will send that too
like blah blah
There's no message arg in on_message
This only applies to commands
Generally in python it means "all args after are keyword-only"
TypeError: on_message() missing 1 required positional argument: 'member'
oh
message.author.mention
Yeah that's ping
[2022-10-27 16:38:44] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 377, in on_message
await channel.send(embed=embed)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.title: Must be 256 or fewer in length.
Clearly understandable, not gonna explain such an obvious thing, sorry
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.
And google "how to read python traceback"
tysm
ugh
import discord
from discord.ext.commands import Bot as BotBase
class Bot(BotBase):
def __init__(self, *args, **kwargs):
self.channel_cache: dict[int, discord.abc.GuildChannel] = {}
super().__init__(*args, **kwargs)
async def get_channel_from_cache(self, channel_id: int):
if int(channel_id) not in self.channel_cache:
self.channel_cache[channel_id] = self.get_channel(channel_id)
return self.channel_cache[channel_id]
@bot.event
async def on_message(msg: discord.Message):
channel = await bot.get_channel_from_cache(996119147337494538)
if str(msg.channel.id) == "specified channel":
embed = discord.Embed(title=f"New feedback! \n \n User: {member.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
embed.set_thumbnail(icon=member.display_avatar.url)
embed.set_footer(text=f"Requested by {member.name} | {member.guild.name}")
await channel.send(embed=embed)
await embed.add_reaction(':Fishy:')
do something like that
thank you!
I had it alive for a split second, I added the intents part but now it's messed up, dunno how to fit
client = discord.Client()
in without coming up with the intents error still
dont use discord.Client its deprecated
what instead?
!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.
last time I did anything with discord.py was late 2020 so it's been awhile
is it working?
no sadly
the same code?
yep
the self
self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
ctx.voice_client.play(discord.FFmpegPCMAudio(executable="./ffmpeg/ffmpeg", source="./a.mp3", **self.FFMPEG_OPTIONS))
await ctx.send("playing")
It runs through the code, joins vc without any error or warning even send the "playing message" but no audio at all. any clue?
ffmpegpcmaudio dont play any sound
any clue why?
discord.ext.commands
[2022-10-27 16:53:37] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 387, in on_message
channel = bot.get_channel_from_cache(996119147337494538)
AttributeError: 'Bot' object has no attribute 'get_channel_from_cache'
wait
you donโt need the from_cache part
oh
get_channel does just get the channel from the cache
bruh
ill try
where do you define ur bot?
Wait, are you trying to create a cache yourself?
yep
wdym
show me your Bot()
Why? Discord.pyโs bot already has one im pretty sure
*bot = Bot()
Granted, their cache is slow
bot = commands.Bot(command_prefix="-", help_command=None, intents=discord.Intents.all())
just do Bot
not commands.Bot
Do it after you define your Bot class
yea
hm?
Itโs not deprecated?
not?
Yeah
Itโs just the base class
No problem with using Client, just you donโt get all the command stuff that Bot has
def __init__(self):
super().__init__(timeout=None)```
Just to let you know, discord.Client is not deprecated. The intents thing became required in discord.py 2.0 though
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I need help๐ค How to make bot dm me when someone sends a help message in discord?
ctx.send
will it dm me?
await user.send("whatever u want")```
user must be there discord.Member object
user: discord.Member```
did it work
let me check
so u wanna do await user.send("text")
and user is defined as a discord.Member object
any option it contains
like mine user_id or mine username?
ok that's why i am checking docs whether it contains any other option
@scarlet aurora I am not getting docs
It's showing team member not a single member
wdym
I am not getting this part await create_dm(user) what user is containing here ?
Kernel will ruin the fun
You can do ctx.user.send("this Dm you")
Most easy way to do it
read this carefully
wdym by "sends a help"
if someone need help then i bot will notify me through dm me
so basically if they send "help"?
hmm
you need to use an on_message event, check if message.content is equal to "help", if it is
then you will get/fetch your user object
user =bot.get_user(yourid) or await bot.fetch_user(yourid)
``` and use `user.send("text u want")` to send a message
ok got it
is there a way to automatically send a message on discord on a channel text at a given delay? if yes, can you give me a link ?
like I want a extension, that runs 24/7 and, at 2 hours delay, from my account types something on some discord server, in some channel text
!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").
use this
thank you โค๏ธ
how to make tickets?
type here #help-croissant #help-orange or #help-honey
Lmao
@slate swan it's showing None user = bot.get_user(myid) print(user)
how to get remaining cooldown of a command for a user, by the user object itself?
its a bit difficult to get the retry time from builtin cooldowns without a context or message object
that means the users id that you passed is not in cache this is likely due to not using members intent
though you can create some kind of MockMessage with the attributes related to the BucketType the cooldown uses
ok
?
so i can go with either a mock ctx or a mock message
yea
you can see what attributes are necessary in the bucket type's source code
https://github.com/Rapptz/discord.py/blob/v2.0.1/discord/ext/commands/cooldowns.py#L64-L69
discord/ext/commands/cooldowns.py lines 64 to 69
def get_key(self, msg: Union[Message, Context[Any]]) -> Any:
if self is BucketType.user:
return msg.author.id
elif self is BucketType.guild:
return (msg.guild or msg.author).id
elif self is BucketType.channel:```
i'll have to go through source code now 
bot command isn't working ```
Traceback (most recent call last):
File "F:\pyenv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "F:\discord bot\bot.py", line 34, in on_message
await message.channel.send(res)
File "F:\pyenv\lib\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "F:\pyenv\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message ``
the variable res is empty
are you remembering to commit to the database
Well, what is None? show the full error ๐
because ctx.guild.id is not in your database
what do you mean? put a record with that guild id in your database
is this someone elses code?
this site is a great place to learn sql https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
guys how can i upload a photo into a embed
i tried using the set_image(url="") but i dont have the url because its a file
url="file://path"
or pass discord.File("path") instead of the url
at least im pretty sure that works
the url scheme should be attachment://, and filename is whatever the file is named when you upload it
see also the FAQ entry about uploading images inside embeds https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image
woops havent done that stuff in quite a while
thx



