#discord-bots
1 messages · Page 194 of 1
if language != "hebrew" or "english":
await ctx.send("Please choose english or hebrew!")
else:
with that, doesnt matter what i am writing its sending the Please choose english or hebrew!
Code?
ah I see now, the if statement is logically incorrect, it should be:
if language != "hebrew" or language != "english":
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Was going to say it 
@shrewd fjordspooooky scarrryyyy sceletons
and next time, please say the problem in the same message you're trying to get help, now we spent quite an unnecessary time just for me to understand what the problem was when you could've said it in the beginning
Oh.
yes thank you!
if language != "hebrew" or language != "english":
await ctx.send("Please choose english or hebrew!")
else:```
where do I put the ephermal (no idea how to spell it) to make it where only the person who reacted with the original menu can see the new menu.
try if language not in ["hebrew", "english"]
kinda also got confused, you should be using and instead of or
if language != "hebrew" and language != "english": should also wokr
ty now ill try figure out how to make the text change somehow
like does it has docs
or somewhere i can read abt it
you'd install some translator library to translate from english to hebrew
or write responses in both of the languages and pick one depending on what language is
Oh no needed i just like do another message w that
yeah that works too
and like do that if language==hebrw and then blah blah
Ye
thanksss!
You need the api token and other stuff, why would u use openai API just for translator tho, instead googletrans exist, and also openai takes time to respond with the answer kek
where do I put the ephermal (no idea how to spell it) to make it where only the person who reacted with the original menu can see the new menu.
people these days think that names slapped with "ai" at the end is just superior to alternatives
Yea, tho ai is still not better than human xd
Im afaik that hebrew translation is very messed up with google traductor
at least some months ago
ping me on reply
set kwarg ephemeral=True in interaction.send
thanks
How can i make this task loop to run 24 hours after it completes updating all users?
@tasks.loop(hours=24)
async def update_elo_ratings():
# Get all the users in the collection
users = await collection.find().to_list(length=None)
for user in users:
summoner_id = user['summoner_id']
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier_and_rank = get_tier_and_rank(summoner_id, RIOT_API_KEY)
elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
await collection.update_one({"summoner_id": summoner_id}, {"$set": {"summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo_rating}})
await asyncio.sleep(10)```
So if it takes 25 hours for it to complete. It should start again after 24 hours after it finished the task.
dear tell me please is it possible to take the name of a function from a variable? for example:
x = "test"
def x()
....
Dynamically create functions?
Seems like an XY problem
help
I would call reset
sorry ik its long
!d discord.ext.tasks.Loop.restart
restart(*args, **kwargs)```
A convenience method to restart the internal task.
Note
Due to the way this function works, the task is not returned like [`start()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.start "discord.ext.tasks.Loop.start").
Already asked
yeah oops
Code:
@bot.tree.command(name='guessinggame', description='Starts a guessing number game.')
async def guess(interaction, ctx, number: int):
emb = discord.Embed(title='Guess the number!', description=f'{interaction.user} has started a number guessing game!')
await interaction.response.send_message(embed=emb)
response = await bot.wait_for('message')
guess = int(response.content)
if guess == response:
await ctx.send('You have guessed the number!')```
ERROR:
```Traceback (most recent call last):
File "main.py", line 25, in <module>
async def guess(interaction, ctx, number: int):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'ctx' is missing a type annotation in callback 'guess'```
Code:
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
bot.add_view(MyButton())
bot.staff_view_added=True
setattr(bot, "db", await aiosqlite.connect("main.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()```
Error when i wrote set_language english:
```Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
!traceback
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 what's the point of setting an db connection if you're going to create another connection anyway
didnt understand
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")
like bc of that?
Yes
oh f
how do i remove it then
does await cursor.execute("ALTER TABLE role REMOVE COLUMN language TEXT") isnt an option
Just remove the line
oh i did
Idk 
i did it as a note
Wait what was ur problem tho xd
class boxengame(discord.ui.View):
@discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler1id == interaction.user.id:
self.bot.boxenspieler1 += 1
button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
await interaction.response.edit_message(view=self)
@discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
print('LOL')
@discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler2id == interaction.user.id:
self.bot.boxenspieler2 += 1
button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
await interaction.response.edit_message(view=self)```
how can i use bot variables here
AttributeError: 'boxengame' object has no attribute 'bot'
at first it was no column language
bot vars
Listen first of all... You should add the language column on the CREATE TABLE execution, then u should add the alter line then run the code, then stop the code, remove the alter line to avoid error and then run the code again
like bot.variableint = 2
Full traceback
U can define in after super().init method
Traceback (most recent call last):
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\cogs\misc.py", line 11, in Spieler1Boxen
if self.bot.boxenspieler1id == interaction.user.id:
AttributeError: 'boxengame' object has no attribute 'bot'
yeah self.bot u can define it on super or on init
like
self.bot="your bot instance here"
Ill try it when i get home tyy
so just add
def __init__(self, bot):
self.bot = bot```
Yes kind of
tho boxensplier1id will still be undefined and throw error
its a class outside of the cog
class boxengame(discord.ui.View):
@discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler1id == interaction.user.id:
self.bot.boxenspieler1 += 1
button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
await interaction.response.edit_message(view=self)
@discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
print('LOL')
@discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler2id == interaction.user.id:
self.bot.boxenspieler2 += 1
button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
await interaction.response.edit_message(view=self)
class misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.boxenspieler1 = 0
self.bot.boxenspieler2 = 0
self.bot.boxenspieler1id = 0
self.bot.boxenspieler2id = 0
self.bot.boxenspieler1name = ''
self.bot.boxenspieler2name = ''```
and if i add it
i get py Traceback (most recent call last): File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: boxengame.__init__() missing 1 required positional argument: 'bot'
You should add it on the boxengame class, the def init method
Because
class variables are protected
i did but i throw me errors
What's your bot instance
It should be something like view=boxengame(bot)
i try this
but now i get ```py
TypeError: View.init() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.init() takes 1 positional argument but 2 were given
@shrewd fjord
Ur view only takes 1 argument but 2 arguments were given
yes but how can i use bot vars in a class ?
You can use it anywhere with bot object
i mean in this
class boxengame(discord.ui.View):
@discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler1id == interaction.user.id:
self.bot.boxenspieler1 += 1
button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
await interaction.response.edit_message(view=self)
@discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
print('LOL')
@discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
if self.bot.boxenspieler2id == interaction.user.id:
self.bot.boxenspieler2 += 1
button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
await interaction.response.edit_message(view=self)
class misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.boxenspieler1 = 0
self.bot.boxenspieler2 = 0
self.bot.boxenspieler1id = 0
self.bot.boxenspieler2id = 0
self.bot.boxenspieler1name = ''
self.bot.boxenspieler2name = ''```
!paste pls I’m on mobile
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.
U can use interaction.bot
- there is no init there
like this ?
async def Spieler1Boxen(self, interaction: discord.Interaction.bot,button: discord.ui.Button):
what's the difference between these two?
how can I make the bot that lets the user add as many arguments? for example, /choose first: johnny second: yes third: papa. the first two will be mandatory and the other will be optional. So 2 mandatory argument and many optional argument
in app commands you cannot have a arbitrary number of arguments
ah, so I need to add a maximum amount
basically yes
😦
Can someone send me the code that makes the status of the bot show how many members there are on the server please
Not possible
what is impossible
Per-guild status
But I see on other servers that have it that they make a Python bot
maybe it tells the total amount of users?
sum([len(guild.members) for guild in bot.guilds]) ?
@left fulcrum
!d discord.ext.commands.Bot.users
property users```
Returns a list of all the users the bot can see.
number of users!= number of members
you're looking for ```py
len([m async for m in bot.get_all_members()])
Do anyone have a good place for me to start with slash commands I have a old project I want to update to using slash commands
Hey guys I got a problem with pm2 could anyone help me out here?
I get this error
[PM2][ERROR] Interpreter python is NOT AVAILABLE in PATH. (type 'which python' to double check.)
When running
pm2 start main.py
What does which python say?
INFO: Could not find files for the given pattern(s).
and its where python because I am on windows
its literally been 1h i've been trying to fix this I feel like im gonna die
You may have forgotten to check the little "Add to Path" when you installed Python
lemme check out but I've added it manually after
btw anyone knows how to send multiple embeds at once? await interaction.response.send_message(embed=embed). For example I run the command /test and I want like 5 embeds getting sent instead of one? do anyone know how. Like what code to write
!d discord.InteractionResponse.send_message < as with most send() methods, you can use the embeds= parameter to send multiple embeds in the same message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
thanks will try
and how do I do if its not a set amount of embeds. For example, when I run my commands and there's more characters than what discord allows. I have a function that says wether its needed to add more than 1 embed. But when I run it its not possible. It only send the first embed
can you send your code?
6000 character limit is per message regardless of how many embeds you have in that one message
so you would have to send multiple messages
10 elements. thatValueError: embeds has a maximum of 10 elements.
hmm lemme see cuz there's a lot of sensitive data
it should be 25 fields not sure what 10 is referencing
lemme send the code here holdon
records_per_embed = 10
counter = 0
embed_number = 1
embed = discord.Embed(title=title.group(1), color=0x5057b5)
sent_embeds = []
for config in data["VenueMapConfiguration"]:
place = config["n"]
for sec in config["secs"]:
row = sec["t"]
stock = sec["q"]
maxprice = sec["max"]
minprice = sec["min"]
counter += 1
embed.add_field(name="Place", value=place, inline=True)
embed.add_field(name="Row", value=row, inline=True)
embed.add_field(name="Stock", value=stock, inline=True)
if stock != 0:
embed.add_field(name="Lowest Price", value=minprice, inline=False)
embed.add_field(name="Highest Price", value=maxprice, inline=False)
embed.add_field(name="-----------------------------", value="", inline=False)
if counter == records_per_embed:
embed.set_footer(text='Mind Solution | Scraper | Embed {}'.format(embed_number),
icon_url="")
sent_message = await interaction.response.send_message(embed=embed)
counter = 0
embed_number += 1
embed = discord.Embed(title="Viagogo negre", color=0x5057b5)
if counter > 0:
embed.set_footer(text='Mind Solution | Scraper| Embed {}'.format(embed_number),
icon_url="")
await interaction.response.send_message(embed=embed)
any idea of how I could make it so it sends more than one embed?
you would use followup for interactions
interaction.followup.send
so initial message would be what you have interaction.response.send_message then you use the followup for further messages
how would I integrate it?
how can i desync commands on tree.sync ?
@chilly dove do yk how I could integrate it into the code?
well it looks like you are doing a embed per item so assuming you keep limits in check then you would have to generate embeds upto 10 or 6000 limit then keep creating embeds in those chunks until you have gone through them all then send the first message as response.send_message then anything after that followup.send
you can use CommandTree.clear_commands then sync with discord that will remove everything from discords side
ok i will try
@chilly dove await self.CommandTree.clear_commands()
AttributeError: 'Bot' object has no attribute 'CommandTree'
should be self.tree
yeah it working tested it already but thank you
someone can explain
discord.app_commands.errors.CommandSyncFailure: Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'exec' defined in function 'Misc3.exec'
In parameter 'Code'
name: Command name is invalid```
how to use more then one variable
i literlly just can use one variable
on tree sync
other will cause command name is invalid
im trying to make a purge command, it deletes the amount of messages you want but it doesn't send the embed
code:
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1063027652065239143)
await interaction.channel.purge(limit=limit)
embed=discord.Embed(title="Logging | Purge Command", desciption="_ _", color=0xFF5349)
embed.add_field(name="Executed by:", value=f'{interaction.message.author}', inline=True)
embed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
message = await channel.send(embed=embed)
embed=discord.Embed(title="Purge Command", desciption="_ _", color=0xFF5349)
embed.add_field(name=f'{interaction.message.author} has executed:', value="Purge Command", inline=False)
await interaction.send(embed=embed)``` no errors.
guys I'm kinda confused, I have a class with my cog in it, how do I load it?
try interaction.channel.send()
Hey do anyone know how to fix this:
@app_commands.command(name="a", description="avenue scraper")
@app_commands.checks.has_role(1069344265404174377)
@app_commands.describe(link="Insert the venue link")
async def test(self, interaction: discord.Interaction, link: str):
embeds = [discord.Embed(description=letter) for letter in link]
for i, embed in enumerate(embeds):
embed.set_footer(text=f'{i+1}/{len(embeds)}')
try:
await interaction.response.send_message(embed=embed)
except Exception as e:
print(f"An error occurred while sending the message: {e}")
await asyncio.sleep(1)
I get this error
An error occurred while sending the message: This interaction has already been responded to before
An error occurred while sending the message: This interaction has already been responded to before
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
Sokobot = Sokobot(bot)
#i imported the Sokobot cog from another file
class ArcadeBot:
@bot.event
async def on_ready(self):
print(f'logging in {bot.user}')
@bot.event
async def setup_hook(self):
await bot.load_extension(Sokobot)
bot.run(TOKEN)
ArcadeBot.setup_hook() missing 1 required positional argument: 'self'
same thing but now i get an error
why doesn't setup_hook get passed the object as first arg?
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 163, in purge
embed=discord.Embed(title="Logging | Purge Command", desciption="_ _", color=0xFF5349)
TypeError: Embed.__init__() got an unexpected keyword argument 'desciption'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'desciption'
you made a typo
it's description
oh
LOL
another error
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 164, in purge
embed.add_field(name="Executed by:", value=f'{interaction.message.author}', inline=True)
AttributeError: 'NoneType' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
fixed that
hi, can you help me? please?
with?
i have 2 traceback in my code...
...
when i enter a word:
2023-02-10 23:05:36 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 32, in on_message
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
when i enter the command:
2023-02-10 23:06:31 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 32, in on_message
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
2023-02-10 23:06:31 ERROR discord.ext.commands.bot Ignoring exception in command niveau
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 71, in niveau
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'
did you copy and paste that code @static holly
yes but did you copy and paste it from somewhere
its very long code
can you answer the question
i dont understand your question
...
code
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1063027652065239143)
await interaction.channel.purge(limit=limit)
purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
await interaction.channel.send(embed=purgelogEmbed)
purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)
await interaction.send(embed=purgeEmbed)```
error
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 172, in purge
await interaction.send(embed=purgeEmbed)
AttributeError: 'Interaction' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'```
it is my code in my project... in VScode
it's sending the first embed to the channel you used the command instead of the one up top
did you get it from a tutorial
or did you code the database feature
nvm
have you tried doing self.bot = await aiosqlite.connect("level.db") in __init__?
no
^
it's interaction.response.send_message
ohh
an interaction can give many types of responses, such as opening a modal, editing a message, sending a message, etc
where to paste this code exactly?
in __init__
in line 15?
"await" allowed only within async function
oh right
try asyncio.get_event_loop().run_until_complete(aiosqlite.connect("level.db"))
in init?
yes
2023-02-10 23:35:49 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
await setup(self)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 130, in setup
await bot.add_cog(levelup(bot))
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 15, in __init__
asyncio.get_event_loop.run_until_complete(aiosqlite.connect("level.db"))
AttributeError: 'builtin_function_or_method' object has no attribute 'run_until_complete'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\main.py", line 24, in on_ready
await bot.load_extension("cogcmd.leveling")
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogcmd.leveling' raised an error: AttributeError: 'builtin_function_or_method' object has no attribute 'run_until_complete'
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
await setup(self)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 130, in setup
await bot.add_cog(levelup(bot))
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 15, in __init__
asyncio.get_event_loop().run_until_complete(aiosqlite.connect("level.db"))
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 625, in run_until_complete
self._check_running()
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 584, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\main.py", line 24, in on_ready
await bot.load_extension("cogcmd.leveling")
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogcmd.leveling' raised an error: RuntimeError: This event loop is already running
@smoky sinew i delete your line?
this is the code, is it right?
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1063027652065239143)
await interaction.channel.purge(limit=limit)
purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
await interaction.response.send_message(embed=purgelogEmbed)
purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)
await interaction.response.send_message(embed=purgeEmbed)```
i'm lost...
oh, so there's no way to send one to a different channel and send the other in the channel that the command run?
you can just get a normal channel object
and call .send
i thought you were sending it to a different channel??
yeah
you literally made a channel variable
one of them, not both
yes
so you send the log to the logging channel and respond to the interaction
you can send messages to whatever channels you want but you must respond once to the interaction
@smoky sinew You don't have a solution to offer me?
do i do
await interaction.channel.send(embed=purgelogEmbed)```
yes but i thought you wanted to send it to a different channel
what is the point of that
don't i need to add channel.send to send it to a dfifernt chanenl?
no? interaction.channel returns the channel the interaction was executed in
you already have a variable called channel
await message.reply(f"message here with buttons", view=SetupProcessButtons())
class SetupProcessButtons(discord.ui.View):
@discord.ui.button(label="Continue", style=discord.ButtonStyle.green)
async def button_callback(self, button, interaction):
await interaction.response.send_message(f"You clicked {interaction.response}!")
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
async def button_callback(self, button, interaction):
await interaction.response.send_message(f"You clicked {interaction.response}!")
Any ideas why only one button is showing?
because the two functions are both called the same thing
you are overriding the continue button with the cancel button
yeah?
rogerrrr so i need to seperate them? SetupProcessButtonsContinue and SetupProcessButtonsCancel say?
i mean why not just call them continue and cancel, don't overcomplicate the name and use snake case
so just send to that?
Could you give a little example? That sounds much better, but im not too sure how you mean
yeah but since the varaiblae is called channel, wouldn't i use channel to send it?
just replace button_callback with continue and cancel
by snake case, i mean naming things like_this instead of LikeThis
PascalCase is used for class naming, and snake_case is used for functions, variables, and pretty much anything else
interaction.channel and channel are two different things, interaction has its own set of variables, like if I were to make a new variable called name = "justin" you wouldn't use print(mudkip.name) to access it if that makes sense
ohhhhh
class SetupProcessButtons(discord.ui.View): # Buttons which get attached when using the /setup command.
@discord.ui.button(label="Continue", style=discord.ButtonStyle.green)
async def button_continue(self, button, interaction):
await interaction.response.send_message(f"You clicked {interaction.response}!") # Button has been clicked
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
async def button_cancel(self, button, interaction):
await interaction.response.send_message(f"You clicked {interaction.response}!") # Button has been clicked**```
somethng like this? @smoky sinew
why even have the button_ there
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 172, in purge
await interaction.response.send_message(embed=purgeEmbed)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
you only have 3 seconds to respond to an interaction
you can send a message like purging... and then edit it once you're done
or you can defer the response
FWIW in the frontend world this is more common
You show a "loading state" and fill in with real data once the network request goes through
im so confused, so i cant send this?
purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)
await interaction.response.send_message(embed=purgeEmbed)```
you can, but you're taking too long deleting the messages
by the time you are done purging, the interaction has already timed out
there's no way to delete messages faster but if you look above i posted some ways to avoid the interaction timing out
would i be able to edit a normal message to an embed?
yes
how would i do that?
How do i check for a phrase in discord user's custom status?
don't think you can, are you trying to give a role?
await interaction.send(f"Purging {limit} message(s) now...")
await edit(embed=purgeEmbed)```
?
no i just want to make a command available only for people with for example "123" in their status
how will discord.py know which message to edit
await interaction.send(f"Purging {limit} message(s) now...")
await edit(content="Purging {limit} message(s) now...", embed=purgeEmbed)```
same thing
how do i do it
first of all, interaction.send doesn't exist i explained that initially and second you need to save the message that it returns and use message.edit
how do i save it'
Fileconfiguration#getConfigurationSection.getkeys(true)
[pos_1, pos_1.x, pos_1.y, pos_1.z, pos_2, pos_2.x, pos_2.y, pos_2.z]
why isn't world in there?
nvm
there was an unindented space in the server config
:D
Hey guys do anyone know how tf i am supposed to do here? its been 2h im stuck:
for conf in data["VenueMapConfiguration"]:
embed_var = "embed" + str(counter)
print(embed_var)
embed_var = discord.Embed(title=title.group(1), color=0x50)
embed_var.add_field(name="Venue", value="aa", inline=False)
counter += 1
await interaction.followup.send(embeds=embed_var)
I get this error:
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'viagogo' raised an exception: ValueError: embeds has a maximum of 10 elements.
im trying to send an embed for every time there's conf. So in this case there's conf 5 times. Basically it needs to be like embed1, embed2,embed3 so then I can simply send multiple embeds at ounce
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
token = os.getenv("TOKEN")
# Bot Init
bot = commands.Bot(command_prefix=".")
bot.load_extension("stocks_cog")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
bot.run(token)
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
class StockCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(name="add", guild_ids=[channelid])
async def add(self, ctx: SlashContext, ticker: str):
print(ctx)
await ctx.send("yes")
@cog_ext.cog_slash(name="remove", guild_ids=[channelid])
async def remove(self, ctx: SlashContext, ticker: str):
await ctx.send("no")
def setup(bot):
bot.add_cog(StockCog(bot))
why is the interaction failing
File "main.py", line 157, in <module>
async def purge(ctx, interaction, limit: int):
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'interaction' is missing a type annotation in callback 'purge'```
I’ll pay you to make me a discord bot that allows you to dupe in fn save the world where you type in a command of my choice that gives you access to dupe on save the world. How it should work is you just drop what ever you wanna dupe and leave the game and it’ll be back in your inventory. Dm me I’ll explain more.
this isn't to pay people to make bots for you, it's to get help and ask questions for coding your own
provide code we can’t really help you with just an error message
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(ctx, interaction, limit: int):
channel = bot.get_channel(1073724291515949077)
await interaction.response.send_message(f'Purging {limit} message(s) now...')
await interaction.channel.purge(limit=limit)
purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
await channel.send(embed=purgelogEmbed)```
you can't have a context and an interaction at a same time
remove the ctx
yes we can
Uhh quick question, when timing out a user, what exactly does it mean to use datetime.timedelta and datetime.datetime?
how long they will be timed out for, timedelta and datetime are special classes
so can I use this to pass it onto the timeout duration? duration = datetime.timedelta(minutes=1440)
i think that will work
Yep it did. Thanks 👍
how do i edit a message to an embed
just do await message.edit(embed = embed)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NameError: name 'message' is not defined
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1073724291515949077)
await interaction.channel.purge(limit=limit)
purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)
await interaction.response.send_message(f'Purging {limit} message(s) now...')
await message.edit(embed=purgeEmbed)
purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
await channel.send(embed=purgelogEmbed)```
again, how is the bot going to know what message to edit
you assign the value send_message returns to a variable and then use that variable
and it's pointless having the description set as _ _ anyway because the description isn't required for an embed, in fact, you can make embeds without a title or description
Hey, so for some reason my intent is wrong with discord.py, and I never messed with my main.py folder and yes I have discord.py installed!
intents = discord.Intents.defualt()
intents.all()
bot = commands.Bot(command_prefix='*', case_insensitive=True, intents=intents)```
Idk why but it didn't did this before
ok apparently i'm wrong you need at least one of those but you don't need both
you misspelled default
it still won't work bro
also i don't think intents.all() does anything, Intents.all creates a new instance of Intents
it won't update the previous one
.
what version of discord.py do you have
remove the intents line and print out discord.__version__
Okay
@smoky sinew
that wont work either
discord has not attribute to version
🤨
__version__
did you spell it right?
Yeah
and did you put the underscores?
where do i assign the value
is your file called discord.py by any chance?
no
do you have a folder named discord?
No
have you tried actually running the code and ignoring the error?
message = await interaction.response.send_message(...)
Run pip freeze
there's no guarantee that they will be using the same python
And
???
uninstall discord and just install discord.py
is is it supposed to be like this?
message = await interaction.response.send_message("Purging {limit} message(s) now...", value=1)
await message.edit(value=1, embed=purgeEmbed)```
same thing bro
have you tried actually running the code and ignoring the error?
No
what is value?
then it's probably just a vscode fuck up
this is what I got
what's crazy is that my bot is running currently by my hosting services and it works perfectly fine!
C:\Python310\python.exe -m pip freeze maybe?
Do you really sure that you don't have a folder named discord
message = await interaction.response.send_message(f"Purging {limit} message(s) now...")
await message.edit(value="Purging {limit} message(s) now...", embed=purgeEmbed)```
like this? idk ive never done this before
i think you mean to replace value with content
send_message don't return the sent message anyway
then you will have to get the response another way
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
message = await interaction.response.send_message(f"Purging {limit} message(s) now...")
await edit_original_response(content="Purging {limit} message(s) now...", embed=purgeEmbed)```
interesting
again how will it know what interaction
i guess you can remove the message = part now
i assumed that send_message would return a message
idk
Do you know what instances are
you should probably learn more python before delving into discord.py
^
why are you still using discord_slash??
vanilla discord.py has its own slash command system
oh
dude idk i haven’t made bots in a while i’m just trying to make a simple stock open/close bot
i can give you a simple example of how to use slash commands in discord.py 2.0, other than that i don't know how discord_slash works
that works with me
@app_commands.command()
async def add(self, interaction: discord.Interaction, ticker: str):
await interaction.response.send_message("yes")
@app_commands.command()
async def remove(self, interaction: discord.Interaction, ticker: str):
await interaction.response.send_message("no")
i just havent done this before
this works with cogs?
yep
and what is app_commands
There's discord.py's slash commands walkthrough in the pins
discord.app_commands
Dumb bot
lol
from discord import app_commands ?
that works
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
i’ll get on my pc in a few and test it
im making a coinflip command and need a bit of help
currently what i want is command to be like
!coinflip heads 100
to bet 100 on heads
i know how to make the !coinflip part, but how do i get the bot to be able to read the "heads" and the 100?
do you want a message command?
if so, for the heads you can use a simple if statement, for 100 you can use an integer converter
converters handle the type conversion for you
how do i make it so if i say "!coinflip heads tails 100" it doesnt just assume i bet on heads? and i dont really understand the 100 part
one sec
let me finish eating and then ill type an example
for heads tails it will give an argument error
look up discord.py converters on google
alright
import discord
from discord import app_commands, commands
class StockCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def add(self, interaction: discord.Interaction, ticker: str):
await interaction.response.send_message("yes")
@app_commands.command()
async def remove(self, interaction: discord.Interaction, ticker: str):
await interaction.response.send_message("no")
def setup(bot):
bot.add_cog(StockCog(bot))
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users//Documents/Programming Projects/Stock Opening : Closing Bot/stocks_cog.py", line 2, in <module>
from discord import app_commands, commands
ImportError: cannot import name 'app_commands' from 'discord' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/__init__.py)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Users//Documents/Programming Projects/Stock Opening : Closing Bot/stocks_cog.py", line 2, in <module>
from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/__init__.py)
import discord
from discord import app_commands
from discord.ext import commands
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1073724291515949077)
await interaction.channel.purge(limit=limit)
await interaction.response.send_message(f'Purging {limit} message(s).')
purgeEmbed=discord.Embed(title="Logging | Purge Command", color=0xFF5349)
purgeEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgeEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
purgeEmbed.set_footer(text="Made by justin;#6868")
await channel.send(embed=purgeEmbed)```
the embeds are only sent if you purge 1 message, anything else they don't send but they still get purged
you might have outdated discord.py
a list of number is considered text or bigint in postgres
im so confused with the datatype of a list of userid
its not bigint but i dont think its text as well
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
Either discord has been ratelimited or slash commands didnt sync properly. Not entirely sure because i dont use slash commands.
They took too long to respond to the interaction
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
you're taking too long to respond, again
pip3 update discord?
`what does this do
that's not a command
acknowledge the interaction
you might want to do pip3 install --upgrade discord.py
you need intents
hold on
what would it do if i added it to my purge command
were you using discord.py 1.4 this entire time?
i don't know what the issue is, have you already responded to the interaction when you got that error? are you responding?
you need to respond
/Users//Documents/Programming Projects/Stock Opening : Closing Bot/main.py:12: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension("stocks_cog")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2023-02-10 20:56:25 INFO discord.client logging in using static token
2023-02-10 20:56:26 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: id).
then my logged in message
load_extension is a coroutine now you need to await it
i suggest you look at the migrating to 2.0 guide
do i do await bot.load_extension(path) in my on_ready()
setup_hook is preferred
don't load extensions in your on_ready
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
what if i did:
async def load_stocks_cog():
async with bot:
await bot.load_extension("stocks_cog")
bot.loop.run_until_complete(load_stocks_cog())
No
async with bot?? bot is not a context manager
It is
how
oh it calls setup_hook
Just override setup_hook
async def my_setup_hook():
await bot.load_extension("stocks_cog")
print("Stocks cog loaded!")
bot.setup_hook = my_setup_hook
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
bot.run(token)
how do i get user id from <@user id>?
use a converter
nope
what do you mean nope
What didn't work then
^^
And which part of it?
try subclassing bot
its some huge error message
Then send it
setup function of the extension also need to be a coroutine
And add_cog is also a coroutine
def setup(bot):
bot.add_cog(StockCog(bot))
Ye
Fine 👍
aight its working thx
even if i were to add a message then edit it to an embed, the same thing would happen
show code
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
channel = bot.get_channel(1073724291515949077)
await interaction.channel.purge(limit=limit)
purgeEmbed=discord.Embed(title="Logging | Purge Command", color=0xFF5349)
purgeEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
purgeEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
purgeEmbed.set_footer(text="Made by justin;#6868")
await channel.send(embed=purgeEmbed)```
where are you responding to the interaction
i deleted it because no matter how much messages i purge, the logging embed will always post but with another message both won't work unless you're purging one
Already asked
What's the problem exactly
nono its should be nobody asked
because im nobody
You'd have better chance in #databases and this is not related to discord bots
well your interaction is always going to fail then if you don't include a response
if i have multiple embed or mesages being posted when i run the command, they will only post if only one message is purged whereas if there's only one message or embed no matter how much messages i purge, it'll always post
it works, it says application didn't respond because there's nothing to respond to the command
ok
https://gyazo.com/4a02c85a26e1967e1219a8501e929fa6
look, it works and logs it just doesn't respond with anything because there's nothing to respond to it
Then just respond to it
@uncut flume codeblocks or pastebin please
https://gyazo.com/d29daa725e8b6045a9629b8e5abccd64 now that i added a response, it only responds if i purge only 1
import discord
from discord.ext import commands
class InChannel:
def __init__(self, channel_name):
self.channel_name = channel_name
def __call__(self, func):
async def wrapper(self, ctx):
if ctx.channel.name != self.channel_name:
embed = discord.Embed(
title="Commands only allowed in #commands",
description=f"This command can only be used in the {self.channel_name} channel.",
color=discord.Color.red()
)
message = await ctx.send(embed=embed)
await message.add_reaction("🗑️")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) == '🗑️'
try:
reaction, user = await ctx.bot.wait_for('reaction_add', timeout=30.0, check=check)
except:
pass
else:
await message.delete()
await ctx.message.delete()
return
return await func(self, ctx)
return wrapper
I'm trying to make a custom decorator to block out certain channels from bot commands. When I pass the decorator to any command, the bot stops responding to the command--even in the correct channel. There's no traceback or error message, it just ignores that command with the decorator added below.
@InChannel("commands")
Is that supposed to explain anything
are you talking to me?
Not quite how you make discord.py custom checks
Refer to the documentation here - https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
does discord.py v2 include buttons as well
It does indeed
trying to make a voting system atm
how do i get display name from <@user id>?
im trying to make a private server between a few friends where they can add/remove stocks from a ticker list. what i want to do is have a voting system where all eligible users have to be online (dnd, online, idle) with a 1:2 voting ratio - whichever side wins within 1-5 minutes will be added/removed from the list
use a converter as i have already said
yes
i quit
why
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
this is the error i get if i add a response
then you are taking too long try removing the purge
You should defer the interaction first, then purge the channel, then use followup to send message
bruh
It's easy, just need to use some of data structure elements 👀
i've already been helping him for 4 hours
oh sed, carry on then 
yeah same command though
But since, it's about removing and adding something to the list, probably you should use a database
that won't be necessary
Wont be, but if u close the script the current data will be gone 🗿
Sleep and then send
nah bro what- 😭 it works now, thank u bro
Hello all.. I am new to python, my background is MERN stack - trying to create a bot but not sure how this whole virtual containers thing works. I type pipx list and get :
I am pretty sure it has to do with my path settup and not sure if anyone knows of this error how to fix
i didn't even need to sleep it-
@smoky sinew thank u for ur help 2
Code: py @tree.command(name = 'choose', description = 'Let the bot choose among upto 10 words.') async def choose(interaction, first: str, second: str, third: str = 0, fourth: str = 0, fifth: str = 0, sixth: str = 0, seventh: str = 0, eighth: str = 0, nineth: str = 0, tenth: str = 0): chosen = random.choice(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth, tenth) await interaction.response.send_message(f'`{chosen}` is my choice!')
error:
File "main.py", line 27, in <module>
async def choose(interaction, first: str, second: str, third: str = 0, fourth: str = 0, fifth: str = 0, sixth: str = 0, seventh: str = 0, eighth: str = 0, nineth: str = 0, tenth: str = 0):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
command = Command(
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 393, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 844, in annotation_to_parameter
raise TypeError(f'invalid default parameter type given ({default.__class__}), expected {valid_types}')
TypeError: invalid default parameter type given (<class 'int'>), expected (<class 'str'>, <class 'NoneType'>)```
anyone know what causes a normalizer err
Traceback (most recent call last):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 28, in choose
chosen = random.choice(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth, tenth)
TypeError: Random.choice() takes 2 positional arguments but 11 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'choose' raised an exception: TypeError: Random.choice() takes 2 positional arguments but 11 were given```
Okay, fixed the error, but because of giving the other 8 the value 'None', it returns 'None' when the third one is chosen even the third one has an actual value given by the user.
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
It takes a sequence, read the docs
You are new and you're using pipx? Well nothing wrong with it just weird how beginner even encountered it
Try using venv+pip instead, that helps to understand concept of virtual environment better
!venv
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Oh heck instead of doing all those arguments just make a converter or even convert string in the code itself, split provided string and map it to int that's it
thanks x
!e py inp = "15 10 20 635" ls = list(map(int, inp.split())) print(ls)
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
[15, 10, 20, 635]
Its already been fixed by the members of discord.py server
I mean those arguments are hell-like structure which is totally unnecessary
I don't know what members helped you but they didn't seem to understand that or consider it minor factor
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, member: discord.Member):
channel = bot.get_channel(1073724291515949077)
await member.unban()
unbanlogEmbed=discord.Embed(title="Logging | Unban Command", color=0xFF5349)
unbanlogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
unbanlogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
unbanlogEmbed.set_footer(text="Made by justin;#6868")
unbanlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=unbanlogEmbed)
unbanEmbed=discord.Embed(title="Ban Command", color=0xFF5349)
unbanEmbed.add_field(name=f'{interaction.user} has executed:', value="Unban Command", inline=False)
unbanEmbed.set_footer(text="Made by justin;#6868")
unbanEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=unbanEmbed)```
this is my code, i want to make it so i can unban with the user id or user and # (because obviously those are the only 2 ways, any help will be appreciated
my question was basically something else
lol
its also not possible to add as much arguments in interaction
That question already was answered to, I know, that was a suggestion
Yeah I advised to have a single argument
And convert it to list
nah. thats so easy
^
I wouldn't consider eleven? parameters a good thing considering they all just get put into a list
That's up to you, just telling it is a bad way
fr, why the heck is int doing there
Convert it to actual integer
Then don't convert it 🤷
For name+discrim you can search through guild.bans(), for ID use await guild.unban(discord.Object(id))
Simple
Then just split it? In your code you typehint every argument with int for some reason tho
wait, the space splits the words right. then what if the user wants two words as one string. for example "exenifix cool, catgal cool, siam dumb"
Raise conversion error
!e
s = "blah, blah"
print(s.split(", "))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
['blah', 'blah']
And yeah don't call yourself dumb. Better term is "less experienced"
More correct term I meant
kek
im saving
great idea. I am removing the hell arguments
is guild = interaction.guild a thing? 💀
thanks for shorting my arguments.
@bot.tree.command(name="kick", description="Kicks the specified user with a reason.")
@commands.has_permissions(kick_members=True)
async def kick(interaction, member: discord.Member, *, reason:str):
channel = bot.get_channel(1073724291515949077)
if member.id == interaction.user.id:
await interaction.response.send_message("You can't kick yourself!")
elif member.guild_permissions.administrator:
await interaction.response.send_message("You can't kick an admin!")
await member.kick(reason=reason)
kicklogEmbed=discord.Embed(title="Logging | Kick Command", color=0xFF5349)
kicklogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
kicklogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
kicklogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
kicklogEmbed.set_footer(text="Made by justin;#6868")
kicklogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=kicklogEmbed)
kickEmbed=discord.Embed(title="Kick Command", color=0xFF5349)
kickEmbed.add_field(name=f'{interaction.user} has executed:', value="Kick Command", inline=False)
kickEmbed.set_footer(text="Made by justin;#6868")
kickEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=kickEmbed)```
it doesn't log when i try to ban the admin but it does when i try to ban myself, is it possible to make it so it doesn't log for myself either?
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
bot.add_view(MyButton())
bot.staff_view_added=True
setattr(bot, "db", await aiosqlite.connect("main.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER, language TEXT)")
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")```
so i did that and now when trying to run this command-
```py
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()```
it writes
```InterfaceError: Error binding parameter 0 - probably unsupported type.```
like i wrote that and tried doing
await cursor.execute("ALTER TABLE role DROP COLUMN language TEXT")
but then shows this error
you don't need to mention type of the column when dropping it
then just language?
yes.
oh now works
tyyyyy
why does it say "[Errno 2] No such file or directory"
i dont know of what im supposed to fix
it means the path you provided doesnt exist..
OperationalError: no such column: language
shows that error but i do have this column
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER, language TEXT)")```
check the db with pgadmin
wdym? sqlite explorer?
okay
what is the error "logging in using static token" supposed to mean?
i clearly used the correct token from the discord developer portal
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.
I did that and it got InterfaceError: Error binding parameter 0 - probably unsupported type. again
send code and full traceback
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
bot.add_view(MyButton())
bot.staff_view_added=True
setattr(bot, "db", await aiosqlite.connect("main.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()```
``` File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 79, in set_language
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.```
why does this show an error? I don't get of whats wrong with this
print language and check what datatype it is
it is supposed to be a string
okay
What error is it then
No one can help without knowing the error
whats the error
(None,)
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
print(language)
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()```
its a logical error then figure out how your function is supposed to work
wdym
imagine helping in Hebrew
That's simple variable assignment, why wouldn't it be a thing
idk lmao
Code:
@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
bot.add_view(MyButton())
bot.staff_view_added=True
setattr(bot, "db", await aiosqlite.connect("main.db"))
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
await db.commit()
Error:
InterfaceError: Error binding parameter 0 - probably unsupported type.
^ anyone?
Full traceback please, unclear where exactly it occurs
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 80, in set_language
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.```
Print language and try to refactor code so you don't have that if-else hell
Code is really hard to read due to excessive nesting
true
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
if language ==None:
await ctx.send("Please write `hebrew`/`english`")
else:
if language not in ["hebrew", "english"]:
await ctx.send("Please choose english or hebrew!")
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
language = await cursor.fetchone()
print(language)
if language:
await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
else:
await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
await ctx.send(f"Successfuly set the helpme language to - {language}")
``` like that?
Indent it
language=....
print(....)
Then it's triggering else statement
What's the problem btw?
InterfaceError: Error binding parameter 0 - probably unsupported type.
^
I want to make a bot which will reply/send .MP4/.jpeg of the meme I wanna share
Hello guys who could help me with interaction.followup.send it’s been since yesterday I’ve been trying to fix my code but doesn’t work
I have made a loop that sends an embed for every item I have
But it simply doesn’t work any idea of how I could do it ?
doesn't work does not explain the problem
Yeah hold’on I have the error
for conf in data["VenueMapConfiguration"]:
embed_var = "embed" + str(counter)
print(embed_var)
embed_var = discord.Embed(title=title.group(1), color=0x50)
embed_var.add_field(name="Venue", value="aa", inline=False)
counter += 1
await interaction.followup.send(embeds=embed_var)
I get this error:
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'viagogo' raised an exception: ValueError: embeds has a maximum of 10 elements.
help
im trying to send an embed for every time there's conf. So in this case there's conf 5 times. Basically it needs to be like embed1, embed2,embed3 so then I can simply send multiple embeds at ounce
What is conf and where is it supposed to be
Yeah
@bot.tree.command(name="kick", description="Kicks the specified user with a reason.")
@commands.has_permissions(kick_members=True)
async def kick(interaction, member: discord.Member, *, reason:str):
channel = bot.get_channel(1073724291515949077)
if member.id == interaction.user.id:
await interaction.response.send_message("You can't kick yourself!")
elif member.guild_permissions.administrator:
await interaction.response.send_message("You can't kick an admin!")
await member.kick(reason=reason)
kicklogEmbed=discord.Embed(title="Logging | Kick Command", color=0xFF5349)
kicklogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
kicklogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
kicklogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
kicklogEmbed.set_footer(text="Made by justin;#6868")
kicklogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=kicklogEmbed)
kickEmbed=discord.Embed(title="Kick Command", color=0xFF5349)
kickEmbed.add_field(name=f'{interaction.user} has executed:', value="Kick Command", inline=False)
kickEmbed.set_footer(text="Made by justin;#6868")
kickEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=kickEmbed)```
it doesn't log when i try to kick the admin but it does when i try to kick myself, is it possible to make it so it doesn't log for myself either?
prints (None,)
And about refactoring, you should just do this where possible
# how you do
if cond:
# if stuff
else:
# else stuff
# how you should do
if cond:
# if stuff
return
# else stuff```
Nesting level will be greatly reduced
So basically, fetchone returns tuple containing language, you just need to get the first element, it will be the value you need
yep!
And that's why I dislike standard sqlite wrappers / aiosqlite
Those tuples everywhere are annoying
^^
what do i define hebrew to be like hebrew=the embed or like what
Because your kick is in elif block
And you are missing return statements in those blocks
Conf is the amount of item there is in the data
And I genuinely don’t know how to do anymore I’ve tried everything.
Should look like this
if member.id == interaction.user.id:
await interaction.response.send_message("You can't kick yourself")
return
if member.guild_permissions.administrator: # not even necessary to use elif
await interaction.response.send_message("You can't kick admin")
return
# the rest of code```
@clear elm
I mean what is its type and how it looks like
Well it’s a list of data in a json
But what matters is that it doesn’t send multiple embeds
oh, thanks
It only send one
!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/opecudunol i tried doing it like that what did i do wrong
Still doesn't provide me much info. I need data like "its type is dict[str, str] and it consists of item names as keys and item descriptions as values"
And example like how the dict actually looks like
@slate swan you still have lots of if-elses, rethink of logical structure. What do you want your code to do?
if language is hebrew then send the hebrew embed or if the language is english then send the english embed
And if language is neither of them send "bad language" embed right?
yes
guys how do I make slash commands work inside a cog? I used the @app_commands.command(name="...", description="...") but I can't see them
Load the extension, add the cog, sync the tree
ah I thought it synced automatically
@slate swan ok then beginner-friendly way is like this
if language == "lang1":
embed = discord.Embed(...)
elif language == "lang2":
embed = discord.Embed(...)
else:
embed = discord.Embed(...)
await inter.send(embed=embed)```
If there are more languages better to use dict
omg i forgot about the " option
Generally it's better to use the dict
Okay but other than that I’m trying to understand how to do a loop that sends multiple embed like. Forget my code, I’m trying to do a loop like let’s say y = 5 then it sends 5 embeds. Do yk how ?
how do I make a calculate command in discord.py. for example: /calculate problem: 6+9/3*2-4 ||i am dumb||
Simple list comp and provide it to embeds kwarg
await inter.send(embeds=[discord.Embed(description=f"Number {i}") for i in range(5)])```
!pypi strmath is good
btw this didn't work
skill issue
💀
What errors did you get and what is your code
error:
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 886, in _invoke_with_namespace
transformed_values = await self._transform_arguments(interaction, namespace)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 852, in _transform_arguments
transformed_values[param.name] = await param.transform(interaction, value)
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 181, in transform
return await maybe_coroutine(self._annotation.transform, interaction, value) # type: ignore
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/utils.py", line 662, in maybe_coroutine
return await value
File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 620, in transform
raise TransformerError(value, self.type, self)
discord.app_commands.errors.TransformerError: Failed to convert justin alt#6346 to Member```
code:
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, member: discord.Member):
channel = bot.get_channel(1073724291515949077)
guild = interaction.guild
await guild.unban(discord.Object(id))
unbanlogEmbed=discord.Embed(title="Logging | Unban Command", color=0xFF5349)
unbanlogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
unbanlogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
unbanlogEmbed.set_footer(text="Made by justin;#6868")
unbanlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=unbanlogEmbed)
unbanEmbed=discord.Embed(title="Ban Command", color=0xFF5349)
unbanEmbed.add_field(name=f'{interaction.user} has executed:', value="Unban Command", inline=False)
unbanEmbed.set_footer(text="Made by justin;#6868")
unbanEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=unbanEmbed)```
what is the function for showing errors?
You need to do it like this, you can't convert banned member to User if bot doesn't share guilds with them and you can't convert it to Member at all
async def unban(inter, user: str):
try:
user = int(user) # try to convert to ID
await guild.unban(discord.Object(user))
except ValueError:
# do bans search```
@clear elm ^
for the calculate command ^^ (if user adds wrong problem)
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(inter, user: str):
try:
user = int(user)
await guild.unban(discord.Object(user))
except ValueError:
channel = bot.get_channel(1073724291515949077)
unbanlogEmbed=discord.Embed(title="Logging | Unban Command", color=0xFF5349)
unbanlogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
unbanlogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
unbanlogEmbed.set_footer(text="Made by justin;#6868")
unbanlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=unbanlogEmbed)
unbanEmbed=discord.Embed(title="Ban Command", color=0xFF5349)
unbanEmbed.add_field(name=f'{interaction.user} has executed:', value="Unban Command", inline=False)
unbanEmbed.set_footer(text="Made by justin;#6868")
unbanEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=unbanEmbed)```
is that right @vale wing
yo anyone wanna help me:
this is the problem Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install discord.py':
@vale wing
Thanks this works well mate, but how would you add field to it?
await interaction.response.send_message(embeds=[discord.Embed(description=f"Number {i}") for i in range(5)])
Just use normal for loop at this point
wym?
okay figured it out
embeds = []
for i in range(5):
embed = discord.Embed(description=f"Number {i}")
embed.add_field(name="Field 1", value="Value 1")
embed.add_field(name="Field 2", value="Value 2")
embeds.append(embed)
await interaction.response.send_message(embeds=embeds)
i dont even know how to save variable as list at this point for my discord bot
You can fluent-chain
Loop probably will look better tho
https://paste.pythondiscord.com/ruteqadixu
that problem now
send screenshot of the db
can someone take a look at my bot and tell me where the best place/way to sync commands would be? https://paste.pythondiscord.com/soqazaricu
changed it to
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT language, role_id FROM role WHERE guild = ?', (ctx.guild.id,))
language, role_id = await cursor.fetchone()
if role_id:
role = ctx.guild.get_role(role_id[0])```
and now
``` File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 873, in prepare
self._prepare_cooldowns(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 856, in _prepare_cooldowns
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
nextcord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 1.39s
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 141, in h
role = ctx.guild.get_role(role_id[0])
TypeError: 'int' object is not subscriptable```
Only if people really read the error
role_id is an int
istg
wdym
let me redo
setup_hook()
Can anyone give me why when I try to unban someone there is an error:
discord.ext.commands.errors.MemberNotFound: Member "Freejakob#6358" not found.
Code:
@client.command()
@discord.ext.commands.has_role("Creator")
async def unban(ctx, *, member:discord.Member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entrys in banned_users:
users = ban_entrys.user
if(users.name, users.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(users)
await ctx.send(f"{users.mention} has been unbanned")
print(f"{member} has unbanned {users}.")
return
it returns as none?
:v
isn't setup_hook() ratelimited as on_ready()?
!e
my_int = 34
print(my_int[0])
@quasi thorn :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: 'int' object is not subscriptable
anyone?
oh thought i needed it
smh
you can string your int, take first index and then return it to int
worked
no
well i thought i needed it cuz it worked the whole time
yeah
Anyone, please help
That member doesn't exist
I've never done anything like that, but wouldn't member search be based on Id?
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
just guessing
The bot can't find users that is not in the server
Just use IDs, what is wrong with it
Then, how to repair it?
try except
And why are you trying to unban a member with slash command
I am not.
Discord won't show users that aren't in the server
?
it did-
@commands.command()
async def unban(self, member: discord.Member) -> None:
try:
member.guild.unban(member)
except discord.NotFound:
print("member not found")
is really that hard to read teh docs?
insert it?
discord.User != discord.Mmeber
what?
You can't get a member object that is not in the guild (banned member)
Like what is full code?
I aint the one coding it
that's right
@commands.command()
async def unban(self, ctx: commands.Context, user: discord.User) -> None:
try:
ctx.guild.unban(user)
except discord.NotFound:
print("member not found")
I still preffer to use user
because if they pass name and # or a mention it will still parse as a user
just preferences
I don't really get the trend that people keep making a command that Discord already has
x2
(╯°□°)╯︵ ┻━┻
he opened a post xd
Why am I seeing the error
discord.ext.commands.errors.MemberNotFound: Member "Cordes#9576" not found.```
When I'm using:
```python
@whois.error
async def whois_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MemberNotFound):
await ctx.send(f" I could not find the user `{error.argument}`.")```
The bot sends the message that it cannot find the user. But it also raises an error in the logs and I don't understand why.
do you have a global/cog error handler too?
Oh yeah you are right, I'm using this as well:
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.send(str(error))
elif isinstance(error, commands.CommandNotFound):
pass # Do not handle this error and simply ignore it
else:
# Handle other errors here
raise error```
those handlers will be triggered after the command's error handler so you need them to determine whether they should handle the error
d.py's default is to check for the presence of a cog/command error handler, but a more flexible alternative imo is setting some kind of handled attribute on the context and checking for that
@hushed galleon Could I simply add another elif clause to handle the MemberNotFound error?
then you'd be responding to the error twice
e.g. ```py
@my_command.error
async def on_my_command_error(ctx, error):
... # do some handling
ctx.handled = True
@bot.event
async def on_command_error(ctx, error):
if getattr(ctx, "handled", False):
# a cog or command handler handled this already, ignore it
return
... # otherwise handle the error like normal
consider using the command extension for prefix command instead of using startwith + on_message
first example is with command extension, the second is your approach which is not great
bot = commands.Bot('!', intents=...)
@bot.command()
async def my_command(ctx):
await ctx.send('hello')
``` instead of ```py
client = discord.Client(intents=...)
@client.event
async def on_message(message):
if message.content.startwith('!my_command'):
await message.channel.send('hello')
For details: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#ext-commands-commands
how do i add a normal non activity sts to a bot
like the sts i have right now
Hey guys, How to make like daily rewards?
like database.
and add there a player username if he does a command and add coins to the balance
You can't
Best implementation would be this
- Database should have a table with
idandclaimed_atcolumns - When user tries to claim daily, check if user is even present in table and if more than 1 day passed from last claim
- Update claim time in database
someone knows how to sort HybridCommands using sorted ?
key kwarg
If you mean sorted by name it's just py sorted(commands, key=lambda x: x.name)
Pretty sure they have name attr
i try
thank you it worked ❤️
If I like make bot offline, database will save?
Hi I am new to using cogs and I wanted to know if I have to register a cog each time when my bot comes online with "client.add_cog()" or only once.
Every time
ok thanks
How to create a json database (I am making daily reward in a bot)?
JSON is not a database
Use sql
||using js as db is addictive||
Can you help me create daily reward system in DMs?
when i use the change_presence function to set a status (dnd, idle , online ) for bot
it removes the previous activity status if its not provided while using the function
how can do it so it only changes the status and dont effect the activity status
never knew you could use js as a database
need a help
how to get a refresh token in the client credentials flow in spotify?
you'll have to give it the text same as the previous one
is this related to discord bots?
where to ask for spotify api?
Can anybody make me a daily reward command?
#python-discussion perhaps? not sure
lol
thanks
You will not learn anything from being spoonfed
Other than keep asking for more
I am trying, I have some code but idk why the errors keep being
I have this:
@client.command()
async def daily(ctx):
with open ("streak.json","r") as f:
data = json.load(f)
streak=data[f"{ctx.author.id}"]["streak"]
last_claim_stamp=data[f"{ctx.author.id}"]["last_claim"]
last_claim=datetime.fromtimestamp(float(last_claim_stamp))
now =datetime.now()
delta = now-last_claim
print(f"{streak}\n{last_claim_stamp}\n{last_claim}\n{now}\n{delta}")
if delta< timedelta(hours=24):
await ctx.send('YOU ALREADY CLAIMED YOUR DAILY in 24 hours')
return
if delta > timedelta(hours=48):
print('streak reset')
streak = 1
else:
streak+=1
daily = 45+(streak*5)
data[f'{ctx.author.id}']["streak"]=streak
data[f'{ctx.author.id}']["last_claim"]= str(now.timestamp())
with open("streak.json","w") as f:
json.dump(data,f,indent=2)
embed = discord.Embed(title="Daily", colour=random.randint(0, 0xffffff), description=f"You've claimed your daily of {daily} \n Not credited")
embed.set_footer(text=f"Your daily streak : {streak}")
await ctx.send(embed=embed)
learn sql and then come back to this command, it will be light work
uh
oh thanks
Thanks
how can i get the current activity status of the application?
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
Honestly I don't know if there's a better way, you can search docs by yourself, there might be
idk I just have this shit habit of asking questions here which I can Google
File "<frozen os>", line 679, in getitem
KeyError: 'mongodb://127.0.0.1:27017' why cant get it working
someone please explain why my commands aren't loading 😭 https://paste.pythondiscord.com/foviqudika
also plez don't hit me with the 'don't autosync', I will change it later; I just want my commands to work
because you didnt load the extension?
Because you never load extension
zam I was sure I had it loaded
Ig I accidentally deleted it with one of my many ctrl z
Is it a cat

Yeah clearly the murder is a cat with hands
which line i should call the function?
Middl-
!d asyncio.run
asyncio.run(coro, *, debug=None)```
Execute the [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) *coro* and return the result.
This function runs the passed coroutine, taking care of managing the asyncio event loop, *finalizing asynchronous generators*, and closing the threadpool.
This function cannot be called when another asyncio event loop is running in the same thread.
If *debug* is `True`, the event loop will be run in debug mode. `False` disables debug mode explicitly. `None` is used to respect the global [Debug Mode](https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode) settings.
This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.
Example...

@naive briarHey, do you know anything about \MONGODB_URI = os.environ
there's no point of using bot.start there tho
instead of the load function, setup_hook could be used, and the bot started with normal bot.run()
for?
Gf 
*gift link.
i'm confuse about the coro thing
@vale wing@slate swan sorry for ping, but I loaded and still nothing showing up
now my on_ready() looks like this
async def on_ready():
print(f'logging in {bot.user}')
await bot.sync_commands()
await bot.load_extension('cogs.sokobot')
why it's not working?
Use setup_hook instead of on_ready
you need to sync after loading the cog
What is coro
You don't just copypaste function signature
what you are doing is ```
- sync the commands
- load the cog
what you should do ispy - load the cog
- sync the cmds
lemme try
And yeah do both things in setup_hook @quasi thorn
HEHEHEHAW IT WORKS
async def main():
...
asyncio.run(main())```
simply use bot.run() why are you even using .start() when you don't understand how coros work
you can load the cogs in setup_hook instead of the load coro
is setup_hook less ratelimited than on ready or sum?
I checked the docs but it doesn't say anything regarding ratelimit
on_ready can be called multiple times
wait wha
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
Or you're calling it yourself I guess
Also just telling you can use this instead of listdir with condition, pathlib is a cool thing trust me
from pathlib import Path
for p in Path("cogs").glob("*.py"): # this will basically iterate over py files in cogs folder, you can even include subdirs files if you provide "**/*.py" to glob
...```
...
strange...
I don't spanish or whatever that is
Could you translate that please?
Ah wait it's FileNotFoundError
You provided absolute path, while you need the relative one, just add a dot before slash so it looks like this ./cogs
./ is current directory, / is filesystem root
Read this again
that's was me trying to fix it removing the "." thing, then when i put the "." thing the same error continues
Ctrl+shift+p -> Python: Select Interpreter -> select interpreter which you installed dpy into. Better use venv tho
And here's venv guide for vsc https://github.com/Exenifix/discord-bots-tutorial/blob/master/guide/01-installation.md#visual-studio-code
okay, it worked
File "C:\Users\Gabriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "c:\Users\Gabriel\Desktop\projetos python\RP Utilities\cogs\Ping.py", line 4, in <module>
class Ping(commands.cog):
File "c:\Users\Gabriel\Desktop\projetos python\RP Utilities\cogs\Ping.py", line 8, in Ping
@commands.cog.listener()
^^^^^^^^^^^^^^^^^^^^^ ```
What a confuse error
Case matters
@commands.Cog.listener()
And everywhere in your code it should be commands.Cog
Python is case sensitive 
Yeah alright told them
In fact, every language probably is
I feel like pascal isn't
And I heard that assembly isn't although I am very unsure about both
Yeah pascal isn't
I wonder who even uses pascal except schools 🧐
Yeah assembly is insensitive too
I was forced to learn it at school and I didn't like it at all 💀
the problem of being insensitive is that it limitate the number of variables you can use
but also have their unknown advantages
I avoid getting off-topic
is there a command that separate strings?
from python?
i'm planning to make a bot that rolls dice
like 1d20 + 1dx + y... ETC
is client.start a thing?
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect").
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
say I have a select menu right how could I make it where under certain circumstances it won't allow them to click a certain one
like for example say I make a if statement, say their username doesn't have a t in it
or their account was made to recent
except sql 
File = [
discord.File("./cogs/create/img/create_img.jpg"),
discord.File("./cogs/create/img/create_th.png"),
]
embed.set_thumbnail(url = 'attachment://create_th.png')
embed.set_image(url = "attachment://create_img.png")
embed.set_footer(text="text", icon_url= ctx.guild.icon.url)
await ctx.delete()
await ctx.send(file = File, embed = embed)
Dear tell me please. It is not possible to send 2 images to embed at once. returns the following error
pycord
okay, guys how do i get arguments from a command?
like, an argument insertion?
to my cog?
files=File
Oh thanks for helping
can only the user who created a view interact with it?

