#discord-bots
1 messages · Page 241 of 1
yeah bro where are you even defining client???? 💀 you didnt have it defined in the code you originally sent
@twilit grotto wdym?
you don't have client defined brodie
import discord
client = discord.Client()
If you're using prefix cmds (So you need the message intent):
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
Just make sure this is enabled in the discord developer application settings
^
@wintry pebble it says wrong token passes
but same token works well in another code
then pass the correct user token.
....
Try resetting the token and copying the new one
@wintry pebble
token works with this code
not with this
u here ? @wintry pebble
Do this
thx ❤️
Hey guys how do you protects your api keys? Right now I’m adding them to a seperate config module which is added to git ignore. What is best practice ?
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Environment variables
!dotenv
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
I am facing this error, idk why
File "C:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 3, in <module>
from discord import app_commands
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 50, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)```
either the file does not exist, cannot be accessed yada yada yada. you could reinstall the package, see if that fixes the issue
it responding with 404 indicates that it's up, no?
i am making a command to timeout ppl which searches if the author has required perms but i am faced with an error
if not ctx.author.guild_permissions.timeout_members:
embed = discord.Embed(
title="Missing Perms",
description=f"{ctx.author.mention}, you don't have enough perms."
)
...```
timeout_members does not exist
i understand the problem but don't know the solution
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\PycharmProjects\pythonProject\all projects\Mod bot\Mod bot.py", line 129, in mute
if not ctx.author.guild_permissions.timeout_members:
AttributeError: 'Permissions' object has no attribute 'timeout_members'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\user\AppData\Local\Programs\Python\Python39\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: 'Permissions' object has no attribute 'timeout_members'
here's full error
I need to put a another check in for other codes like 404
which package?
you are importing a name, which doesn't exist in the discord library. so either discord py isn't fully installed or the name doesn't exist
!d discord.Option ?
No documentation found for the requested symbol.
let me check docs
alright
!d discord.app_commands.Choice
class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.
New in version 2.0.
x == y Checks if two choices are equal.
x != y Checks if two choices are not equal.
hash(x) Returns the choice’s hash.
no idea
?
just watch
I won't
the ending 💀 ahah
not bad
run pipfreeze in terminal and lmk the vers of dc
!pastebin
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.
no way i have seen this days before , really
I would like to have several discord bots online at the same time I am programming on pycharm can someone tell me how to do it
you would need to run two separate processes
yes just the page isn't available basically (the page its trying to access) lmao
Can I use on_ready in an extension?
yes
from discord.ext import commands
@commands.command()
async def economy_base(self):
pass
async def setup(bot):
bot.add_command(economy_base)
```
This sound? Gonna use it to contain the DB setup
I would use threading
or if you just need to send api calls I would just use discord's api
im using ffmpeg on a ubuntu server and it didn't work, can someone help me?
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
- Try
sudo apt install ffmpeg - If 1 fails, download ffmpeg binary for linux from https://ffmpeg.org and put the
ffmpegfile into project root; or provide the path to the ffmpeg file where needed
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
!d PIL
from my understanding you can make buttons like this in discord.py
class Example(View):
def __init__(self):
super().__init__()
@discord.ui.button(label="test", style=discord.ButtonStyle.blurple)
async def test(self, interaction: discord.Interaction, button_object: discord.ui.Button):
await interaction.response.send_message("hello")```
i'm wondering if its possible to have a button stored in a variable like an object? also im not sure exactly how this works behind the scene
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
sombody know how to make (try my command)??
discord.py
what?
i'm wondering if its possible to have a button stored in a variable like an object?
Yes, you can
how
Heres an example
class CounterButton(discord.ui.Button):
def __init__(self, label='0', **kwargs):
super().__init__(label=label, **kwargs)
self.counter = 0
async def callback(self, interaction: discord.Interaction):
self.counter += 1
self.label = self.counter
await interaction.response.edit_message(view=self.view)
view = discord.ui.View()
view.add_item(CounterButton(style=discord.ButtonStyle.primary))
view.add_item(CounterButton(style=discord.ButtonStyle.success))
view.add_item(CounterButton(style=discord.ButtonStyle.danger))
await ctx.send('Click counter button below', view=view)```
You can subclass ui.Button
how can I made this option??
you can't
How do you make the bot return with only you can see this message with slash commands?
Set the ephemeral kwarg to true in response.send_message
Example?
Never seen that
Of what? I already told you what to do
How do I set it true?
interaction.response.send_message('Some message', ephemeral=True)
Nvm found it in the docs
Thanks
thank you man
wait a sec I was just trying to do this.. is it possible to make a message appear to mods only?
I couldnt figure it out
Yep stick it in a mod only channel.
ahhh yeah,
the only way I could find was permissions
I guess its impossible in a text channel where others can read messages
How do I send a link to a command?
Like when someone clicks the link the command is typed for them
Is discord.py even compatible with 3.11.2 🤔
Send a link in chat which when clicked, it writes the command in their text box?
I don't think that's possible.
I've seen it used on bots before
I think in some descriptions
.
That /help link types it out in chat when I click it
read that
So you cant?
I guess it is possible. I have no idea how you'd do that. Discord never had functionality like that
What I notice is what the command seems to be in, it is like an opened spoiler thing which works like the epoch timestamp.
Unless you can set up a slash command and have it some sort of </help> format
Not sure how they achieved this, but, it is smart.
well there's a way to do it but it doesn't work on every platform
like on browser
</some_command_name:0>
</some_command_name:0>
guild_subscription_options=discord.GuildSubscriptionOptions.off())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'GuildSubscriptionOptions'
i m getting this error help
As the error says
GuildSubscriptionOptions doesn't exist in discord.py or any other library out there
how to solve that
kk
</UWU:0>
help
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.
i alr enter token
TOKEN = " my token "
do you know python?
yes
what m i missing
show your entire bit of code but be sure to censor your token out
no need
let him think a bit
150 lines
search that exact error in google @sturdy fractal
bro i m stuck since 30 min
then I'd personally recommend learning python first
lmfao i just realized.
i used chatgpt it says to do
TOKEN = " my token "
i alr have that in code
yeah maybe that's why it doesn't work
pls help i m getting annoyed now
do u have it defined as my token
anyone who has a pretty basic knowledge of python would be able to fix it
or is it an actual token
huh i tried entering token directly still same error
in " i put my actually token
if you actually have a token variable then it wouldn't say it is missing
i m calling it
client.run(TOKEN)
but it is saying its missing
TOKEN ="MTEwNjQ3NDM3NT6CQSpsipHEadA"
i erased half token
fine
not a valid token
....
yeah, tgat part of the token is public from snowflake id
dude he didn't send the other half
u want me send my actual token bruh?
no
wtf are u thinking decoding it with base64
discord tokens are encoded in base64
you can grab half of a users token from it
or beginning of it
then perhaps show your code
u literally can
the point is he erased half of the token
what's the point in decoding it
i can just reset it bruh
no shit sherlock…
.
see, first part of the token should be the bot id
whole 150 lines?
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.
paste your code without token
i gave u 3rd part
the last part is the actual secret
oh boy.
they can generate one? yes
a vlid one? one in a thousand millions chance
lol
@thin raft
?
check dm
i installed it but the bot cant find the path
can you show your code and files
Then follow the second method
Hi, I'm trying to follow how the discord py bot runs step by step. I cant figure out how to change the default logging level. The default bot_trace_loggers in constants is already set to *.
I don't recall there's anything called bot_trace_loggers
have you read the docs on setting up logging?
https://www.pythondiscord.com/pages/guides/pydis-guides/contributing/bot/#appendix-full-env-file-options Said if its set to * the root logger is set to trace
A guide to setting up and configuring Bot.
that _ at beginning it's a convention or what?
Hi, I have a question.
Let's say I have a command /command [option1] [option2]. I want the choices for the option2 to change, depending on the value of option 1, Is it possible to access the value of option1, then use it for the option2?
are you trying to create a new bot or contribute to the bot used in this server?
At the moment just trying to read the code
I'm following the start up "process" for lack of a better term to see how it works
as I'm looking throught the code I've seen a few log calls which are being filtered out.
https://github.com/python-discord/bot/blob/main/bot/log.py#LL15C15-L15C15 I think it is here
Ah set from level_filter = constants.Bot.trace_loggers
i wanted some help with some code
when i try to fetch id using this
host = ctx.guild.get_member(host_id)
it returns me none even tho the id exists and is present in the server
Whether guild member related events are enabled.
This corresponds to the following events...
I just added that to the code but still same thing
Show the code
I’ll dm you if thats okay?
No
okay i’ll send it here
gimme a bit
``bot = commands.Bot(command_prefix='.')
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
@bot.command()
@commands.has_role(1014148557634289674)
async def winner(ctx, host_id: int, message_id: int):
temp_role = discord.utils.get(ctx.guild.roles, name="commgw cooldown")
host = ctx.guild.get_member(host_id) # Get the Member object
giveaway_message = await ctx.channel.fetch_message(message_id)
giveaway_embed = giveaway_message.embeds[0]
if giveaway_message:
reactions = [reaction for reaction in giveaway_message.reactions if str(reaction.emoji) == '']
if len(reactions) > 0:
participants = []
for reaction in reactions:
async for user in reaction.users():
if not user.bot:
participants.append(user)
if participants:
winner = choice(participants)
prize = giveaway_message.embeds[0].description.split('`')[1]
giveaway_embed.add_field(name="winner", value=winner.mention)
giveaway_embed.color = 0x3C0C0C
giveaway_embed.set_footer(text=f'giveaway ended')
await giveaway_message.edit(embed=giveaway_embed)
await host.remove_roles(temp_role)
await ctx.send(f'Congratulations {winner.mention} ! You won the giveaway of **{prize}** hosted by {host.mention} ')
else:
await ctx.send('No one participated in the giveaway.')
else:
await ctx.send('No one reacted to the giveaway message.')
else:
await ctx.send('Invalid message ID.')``
why don't just typehint discord.Member for host_id
It will give you a list of member to choose from
im not sure how to do that 😭
and what is wrong with this code anyway?
i always get NoneType error
oh it was a text command
you can still @ the user as the input tho
or user id whatsoever
also the message id can be discord.Message
whats this
C:\Users\WIN 7\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.15) or chardet (3.0.4) doesn't match a supported version!
Anyone know how to sync a / command
!d discord.ext.commands.Bot.sync
No documentation found for the requested symbol.
wtf
?
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
then .sync
What's this
idk why it doesn0t detect it
Im still quite confused on what to type
send code
@bot.event async def on_ready(): print(f"We have logged in as {bot.user} and are serving at {len(bot.guilds)} Guilds!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)
Is that it?
yup
you can but only sync when you have changed something
but what if you changed the command params during dev
then you need to restart the bot
then restart it?
you can use a normal command so you don't have to
What's the problem with that?
Sorry what's the code to make it a /command? Is it @bottree or see
it will be called every time you resumed a section
making useless calls as you didn't change anything yet trying to sync
I'm not gonna type a command to sync it. My bot is ont 24/7 once its synced once there's no need to sync it again
on ready can get called multiple times
use setup_hook instead
How would you make a database? and be able to change the value in the database
@stiff fern Hey,, sorry for the ping, I saw that you had asked bout why ur "commands.Cog.listener()" wasnt catching any error
it was cuz we had to pass our app_commands error handler to commandTree
I was wondering if you figured how to pass app_commands error handler to commandTree as I needed help with it
|| p.s. Im so so sorry for the ping, I hope i wasnt disturbing you!||
Perhaps you're looking for a custom CommandTree?
(I don't have the full context from your earlier question, BTW)
with the coming discord update to Usernames will this fk up bots using the likes of, ctx.author,ctx.author.name,interaction.user,interaction.user.name ?
it should not but one thing that may break could be member.discriminator
how to avoid this and just send the embed with 3 complete values ?
My commans is : ```py
@client.command()
async def warstars(ctx, townhall, country):
country = country.lower()
if country in data:
country_code = data[country]
else:
await ctx.send("Invalid country")
url = f"https://www.clashofstats.com/rankings/players/war-stars/{country_code}/{townhall}/1"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
elements = soup.find_all("a", class_="no-link", href=lambda href: href and href.startswith("/players/"))
if len(elements) >= 3:
random_a_elements = random.sample(elements, 3)
#embed = discord.Embed(title=f"3 WarStars accounts local {country}, townhall {townhall}", description=None)
await ctx.send(f"3 WarStars accounts local {country}, townhall {townhall}")
for a_element in random_a_elements:
tags = a_element['href']
pattern = r"/players/(?:.*\-|)([^-]*?)\/"
matches = re.findall(pattern, tags)
for match in matches:
#embed.add_field(name=None, value=match)
await ctx.send(match)
#await ctx.send(embed=embed)
else:
await ctx.send("Pas assez d'éléments <a> trouvés.")```
ahh ok one sec
@client.command()
async def warstars(ctx, townhall, country):
country = country.lower()
if country in data:
country_code = data[country]
else:
await ctx.send("Invalid country")
url = f"https://www.clashofstats.com/rankings/players/war-stars/{country_code}/{townhall}/1"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
elements = soup.find_all("a", class_="no-link", href=lambda href: href and href.startswith("/players/"))
if len(elements) >= 3:
random_a_elements = random.sample(elements, 3)
embed = discord.Embed(title=f"3 WarStars accounts local {country}, townhall {townhall}")
description = ""
for a_element in random_a_elements:
tags = a_element['href']
pattern = r"/players/(?:.*\-|)([^-]*?)\/"
matches = re.findall(pattern, tags)
for match in matches:
description += match + "\n"
embed.description = description
await ctx.send(embed=embed)
else:
await ctx.send("Pas assez d'éléments <a> trouvés.")
```try this
it does the same thing
not working
try what i edited the code to
bro what?
i have no idea
i want the last embed to be smthg like value1 = tag1
value2 = tag2
value3 = tag3
yea i know what you want, the code i sent should only be sending 1 embed with all 3 values in it thats why im confused lmao
ah
So my BOT is storing is own messages, I tried that but isn't working and I don't have any idea why.. Can somebody explain and help me?
this is even worse
especially since your commands might not have been loaded by the time setup_hook is called
i've been doing it wrong this whole time then
whats an ephemeral message
a message that can only be visible to the user after an interaction
does it always have to be after an interaction
yes
so when i try to do a command that's not in my python code or whatever it shows me this thing
does anyone know how to rename it and make it my own?
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
extend this and set bot.help_command
ok ty
why lol, just load the commands before syncing in the setup_hook itself
the only issue here is auto-syncing which is bad bad
i dont know how to do that i just stared coding so, do u have any example i can look at?
you can also just remove the default help command and make your own
Sheesh dude, seems like both of us are in sam shoe.
It's my first day starting, lmao
Being in Sam's shoe mustn't be very pleasant 🥶
🐈
Pycharm?
Afraid that's lib issue you can't really fix, maybe there are type stubs you could search for
yes, do you have a question?
yes
my client wants me to retrieve some data from discord based on some keywords
like if he enters "crypto" he should get servers related to crypto
I need an API service for this
Don't think they have a server search endpoint, but you can double check in the api docs (https://discord.com/developers/docs/intro)
Why tf your client needs that when there's discovery 🧐
It does exactly that and is embedded into discord interface
ok
can bots read embed content?
🔥
I wanna ask "how" here
I use disnake
access the content you want to from the embed object; embed.title, embed.description etvc
all the attributes are listed in the docs
Hi
Hi
how do i read this with json?
import json
with open("filepath/name") as file:
data = json.load(file)
print(data["TOKEN"])
maybe this will work
Hello can you help me for this error
Can you tell us what you're trying to do?
Create slash commands?
Yeah, but what's the purpose of the bot? What's it supposed to do?
verify paypal purchase
With slash commands?
yes
You don't need all that for slash commands, discordpy has native built in support
I can't get the link at the moment but the GitHub has a bunch of examples
how to fix this error?
Well the error is that you're creating an instance of Bot without the required intents kwarg
Also you don't need a client object as well as a bot object since Bot inherits from Client (I'm assuming you are using discord.py)
yes i use discord.py
it will work on embeds
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
and?
And? Read
That's how you make the most basic slash commands
i need fix error
i dont need slash commands
No need of Client and no need of SlashCommand thingy that is some weird third party library
You don't know yourself what you want apparently
this bot has slash commands, the problem is that when I try to run the bot it doesn't work, there is a problem
Error says it all
Missing intents kwarg
Also you don't need bot and client
It's either bot or client
Not both
So delete the entire client line
And add intents=... in our bot instance you create
As well as replace client to bot in that weird and useless SlashCommand thing
right?
No?
I told you
So delete the entire client line
And add
intents=...in our bot instance you create
E.g.
bot = Bot("!", intents=whatever)
intents = bot
do you guys help with javascript too or
What even is a slashcommand object?
Just like you have in client at the moment
Take a wild guess
Not here but you can ask in #ot0-psvm’s-eternal-disapproval
This is a Python server
multiple people can know it
There are JavaScript servers
Python servers are for Python related questions
I can not do bot instance
or just

Do you know Python or are you copying that code from somewhere without knowing what it does at all?
Stragar homie I mean this in the nicest way possible but I think you have some Python practicing to do before Discord bots
bro
Because it doesn't seem like you know, as you just copied whatever in your code without knowing I mean the entire discord.Intents.all() thing
the bot is not mine
!resources then
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
discord.py is not meant for beginners, that's mentioned in their README as well
Take the time to learn at least the basics of Python
Btw enabling all intents is not a good practice
We're here to help with code not how to setup a Discord bot for you.
That's irrelevant either way and we don't know their use case(s), assumptions are worse.
the bot has a problem in the code itself that I don't know how to fix
Then you can open an issue on the GitHub repository where you got the bot
So does that mean u can just enable all?
Without all the changes made here what's the error?
\
You can, if you have valid uses cases for all of them, yes.
^
XD
Open an issue there if you don't know how to fix it
There is nothing as slash_command in dpy
Replace bot = Bot("!") with bot = Bot("!", intents=discord.Intents.all())
There isn't, that's why the bot used some random third party library to have it and be able to use slash_command
So yes, in their case it exists
Worth noting the last commit date - which explains the use of outdated things
new error
My point again, that's 2 years old code that won't work with the current discord.py 2.x version
Zz the code is out dated
Yeah the code is old, I recommend getting something newer.
Open an issue on the repository to get the author to migrate it to 2.x version
Fix it yourself by learning basic Python beforehand, or find something different
This code was written in the dark days of discord.py

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
client.run(TOKEN)```
That won't solve his problem
His code is pretty old
yes it will
just replace bot = Bot("!") with what i sent
I'd say recheck the code
how i integrate the db into my discord bot?
i don't know how i do it, i'm seeing a tutorial that uses psycopg2, but someone that seems experient is teeling me to use asyncpg, well, i will need to learn it (thought it makes sense since discord bot uses asynchronous function)
It won't
does mongoose exist for python
Yeah asyncpg is nice
guys, anyone have a sample to implement my database as a fundamental cog (or just as cog)?
yes, pymongo or async one is motor
guess now i can see how i can implement it
but first i need to know something about discord bot
that is an @twilit aspen that i could use to make it auto-run
like when it initiate the cog it already runs the database thing
this is the sample i got from internet
https://gist.github.com/jegfish/cfc7b22e72426f5ced6f87caa6920fd6
Example code for connecting to and using a postgres database using discord.py and asyncpg. - example_db.py
maybe in __init__?
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\main bot\main.py", line 33, in <module>
bot = commands.Bot(prefix="prefix")
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'
i'm having this error can some1 help me?
its supposed to be
bot = commands.Bot(prefix="-", intents=discord.Intents.all())
same error
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\main bot\main.py", line 33, in <module>
bot = commands.Bot(prefix="-", intents=discord.Intents.all())
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix
it's worked
good job
thanks
np
Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 84, in button_callback
await interaction.channel.send(MyModal(title="Modal via Button"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 72, in __init__
self.add_item(discord.ui.InputText(label="Short Input"))
^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.ui' has no attribute 'InputText'
``` how to fix error ?
code: ```class MyModal(discord.ui.Modal):
def init(self, *args, **kwargs) -> None:
super().init(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Modal Results")
embed.add_field(name="Short Input", value=self.children[0].value)
embed.add_field(name="Long Input", value=self.children[1].value)
await interaction.response.send_message(embeds=[embed])
class MyView(discord.ui.View):
@discord.ui.button(label="Send Modal")
async def button_callback(self,interaction: discord.Interaction, button: discord.Button):
await interaction.channel.send(MyModal(title="Modal via Button"))
@bot.command()
async def send_modal(ctx):
await ctx.reply(view=MyView())
now yes
Is there a way to wait_for for an interaction?
How can I make a system to check if a user is already registered without putting a function before every command to check if they do?
okay, it's almost close for me to finally implement:
Rename your files
my file... uhmm, strange
okay, it's kinda confuse
you mean my .py files?
like bot.py to sometihng else and shit?
@idle lantern
So I'm making something in which the users will have their turn to press a button and as soon as the button is pressed, the program will continue, until then it will be paused? Any way of doing it?
one way would be using the built-in wait()/stop() methods of discord.ui.View (assuming you're using discord.py 2.0)
https://github.com/Rapptz/discord.py/blob/v2.2.3/examples/views/confirm.py
!d discord.ui.View.wait
await wait()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called or it times out.
Let me check thanks
or perhaps an easier solution, depending on what you're doing, is to run whatever code is necessary in the callback of your button
Yea
Because there are some modules with files by those names such as database
their error is a circular import though
if bot.py imports database.py and database.py imports bot.py, you have a circular import which is generally confusing to work with (though not always an immediate error)
oh so it's just the database thing
i would recommend using a context manager to open your database pool instead, that way you cant forget to close it afterwards ```py
async def main():
async with asyncpg.create_pool(...) as pool:
bot.db = pool
await bot.start(token)
asyncio.run(main())```
the problem is me removing theload thing, but let me see this
I made a file called discord.py and when i imported discord module into it I got circular error
right, because if you use import discord inside a script named discord.py, its going to try importing itself
okay, i don't know how i wiil modify this to what you suggested me:
well you already have half the work done there, you just need to connect your database
^
do you see how my example connects to the database?
oh, now i see
like this:
the bot starting would be at the own bot, but i don't know if i need to make the bot.start thing
okay, another error:
you need to assign the .db to the bot varriable not bot module
handling the connection in the same place as your main() function is going to be more convenient than trying to write it in a separate module
i'm planning to make the database thing in a separated class
you should move it to the main file
like, it's to prevent spagetti code
cus my bot will use a lot of database
you can have database logic outside but connect to it in main file
oh i see
so how does moving a couple of lines from your bot.py file to a separate file make it less spaghetti?
and how do i disconect after stopping the bot?
if you use async with, it automatically cleans up the connections for you
when you use context manager it does it for you
oh i see, perfect
if you really wanted to put the function elsewhere, the easier option is adding a parameter to your create_db_pool() function to pass your bot instance, rather than trying to import it from the same file that wants to call it
parameter... uhmm, i don't knw if it's about public, private thing
or protected
but i guess protected would be saifier
who knows?
those concepts dont exist in python, and those are related to class members, not function parameters
def setup_bot_db(bot):
# ^^^ parameter, i.e. an input to your function
pool = await asyncpg.create_pool(...)
bot.db = pool```
i see, it don't use async
oops
nevermind then
okay, i have no idea what parameters i put into my function, guess client?
what object do you want to assign your database pool to?
also it was a demonstration, i still recommend writing the async with syntax in your bot.py file
okay, i have no idea which object i want to assign to my database poool
XD, completely lost, i'm like the a child in a forest
here goes nothing:
Hello, wondering if somebody knows what I've done here,
I wrote some code, quite some time ago, to prevent people that aren't developers on my project from running specific commands. Only I find that now I don't remember why I wrote it like this, I put a function inside of a function to test for these users. The code works, I just wondered if it's written like this because it needs to be, or if there is a tidier way of writing this function.
Developer only command example:
well your boolean return can be refactored into return interaction.user.id in developers, but otherwise thats an acceptable way of writing a check
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.check
i would additionally sync your command to one guild where only your devs can see it
Oh? That's possible?
!d discord.app_commands.guilds
@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.
When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.
Note
Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.
Example...
they're known as guild-specific commands
https://discord.com/developers/docs/interactions/application-commands#registering-a-command
Well well, learning something new once again, thank you very much
right click on 'rpudb' and see if it takes you back to your class, if not then somethings interfering & also, its an async function in your class, you need to await it when calling it
if i click to go to definition it get me back to my class
you have a module named rpudb.py and a class inside it named rpudb, but you are incorrectly referencing the module rpudb instead of the class rpudb.rpudb
also you're closing the pool right afterwards by leaving the indented async with block
ah yeah i didn't realize that
being a novice be like:
if that's the case how i can prevent it from closing?
i'm planning to use the db in cogs
guess that part i would need to implement in cogs instead of in bot
like you said that its closing
thats a different error meaning you're trying to use a variable that isnt yet defined
if your way it worked:
seriously, why not use create_pool() inside main()?
er, you're still closing the pool before your bot has even started
i see
guess the starting thing i need to put inside the async thing
imnw
in this way i got into an eternal loop
now i had an idea, instead of opening the database directly through my main, the database could be momentaneously opened once a person wants to create a character, edit a character, and etc
it would economize in processing time
oh, now i got you
you mean that need to declare it before initiating it inside
but the problem is in which i need to declare it?
as a string?
number?
list?
well, in doubt improvise
time to search for wild variable declaration
opening a connection for every interaction would actually be slower than reserving a connection at the start and re-using it, which is what connection pools are designed to do
yeah someone else already said the same too
well, now i need to declare the rpu_db before the async thing
but since i don't know which declaration is correct (cus i don't know if it's a list, number or string) i will search to turn that variable a wildcard
i have no idea what you're talking about
the box here:
you're assigning the pool to rpu_db which is a local variable, so you will be unable to access it outside of main()
yes, that's why i want to declare it before
i want to declare rpu_db as something that it is compatible
i dont see how that would fix your issue
string, number or list
you mean you want to define rpu_db as a global variable?
yeah, technically
but as compatible to the thing
string, number or list
variables are dynamically typed so it doesnt matter what you assign it to, and i wouldnt bother mocking your connection pool object anyway since it should be an error to try using the database before its connected
hi
a global rpu_db statement would be sufficient to assign it as a global variable, though "bot vars" are usually a better choice since you can access them from anywhere you have the bot instance
mocking is what brazilians most do
e.g. use client.pool = pool, then anywhere you have the client you can acquire a connection with async with client.pool.acquire() as conn
worked in (inf)k
hi so im trying to do a game similar to russian roulette and this is the code and the error i've been getting
TypeError: Client.event() missing 1 required positional argument: 'coro'
does anyone know how to fix this?
also the game cracker, if you want you can mock, since it's a beginner error, i would even make a meme about it
like: when it's your first time learning postgresql
that's not a good way to do it
I think you should use TORTOISE_ORM to load all your data
from os import getenv
from typing import Any, cast
from dotenv import load_dotenv
from dynaconf import Dynaconf
load_dotenv()
class Settings:
"""# Global settings file
Fields:
=> bot
-> token
-> env
=> log
-> level"""
class Bot:
token: str
env: str
class Log:
level: str
emojis: Any
partialemojis: Any
colors: Any
log: Log
settings = cast(
Settings,
Dynaconf(
envvar_prefix="SPOOKY",
load_dotenv=True,
merge_enabled=True,
settings_files=[
"assets/settings/colors.toml",
"assets/settings/emojis.toml",
],
),
)
TORTOISE_ORM = {
"connections": {
"default": {
"engine": "tortoise.backends.asyncpg",
"credentials": {
"host": getenv("DB_HOST"),
"port": getenv("DB_PORT"),
"user": getenv("DB_USER"),
"password": getenv("DB_PASS"),
"database": getenv("DB_NAME"),
},
}
},
"apps": {
"Bot": {
"default_connection": "default",
"models": ["aerich.models", "spooky.models"],
}
},
}
This is how i load my data, I think it will help you for a better logic
What are you using? Is this Py-cord or Discordpy?
like what pip did you run to get this?
like pip install xxxxx
what did you install for this package
okay so discordpy
yes
Honestly that's not how commands should work. Don't do an event, there are already built in functions for commands.
Yeah that's fine.
its @client.event not client.event()
thats the error
Yeah that, but you shouldn't even use an event.
Wait that's not right
from discord.ext import commands
i know dpy, i use it
i have this
sebass
but he doesn't have client.event() he has @client.event()
remove the () from @client.event
i did
?
Yes but still, don't do commands like that dude
i just stared like 2 days ago xd
@finite abyss could you send me your entire code?
use @bot.command()
@finite abyss can you show me your whole code without the token? I'll show you how you do it with commands.
dm or here?
post it here
should i just copy paste?
tes
oh
import discord
from discord.ext import commands
import random
client = discord.Client(intents=discord.Intents.default())
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())
@bot.event
async def on_ready():
print('The bot is now online!')
@bot.command()
async def hello(ctx):
await ctx.send('Hello!')
@bot.command()
async def alex(ctx):
await ctx.send('Alex e prost!')
@bot.command()
async def stramb(ctx):
await ctx.send('Darius o are stramba rau de tort')
@bot.command()
async def dacian(ctx):
await ctx.send('But does this hurt Ciolos?')
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
@bot.command()
async def roll(ctx):
await ctx.send(random.randint(1, 1000))
@bot.command()
async def helpme(ctx):
await ctx.send('`Come here for more help!: https://www.youtube.com/watch?v=dQw4w9WgXcQ`')
@client.event
async def on_message(message):
if message.content.startswith('.chance'):
chambers = [0, 0, 0, 0, 0, 1]
random.shuffle(chambers)
player_chamber = random.choice(chambers)
chambers.remove(player_chamber)
await message.channel.send('`The trigger is pulled...`')
if player_chamber == 1:
await message.channel.send('`Ops, you are dead! Better luck next time!`')
else:
await message.channel.send('`Click! You survived!. You can try again if u dare!')
tell us why
look, you know how to use bot.command() when you use it for everything else.
btw on_message will break all ur other commands
if u dont have a bot.process_commands()
wtf....
nvm he used client and bot
u define bot and client.
that code is cursed bro.
ikr
XDDD
look. get rid of client. use one or the other.
theres no reason to be using discord.Client()
@bot.command()
async def chance(ctx):
chambers = [0, 0, 0, 0, 0, 1]
random.shuffle(chambers)
player_chamber = random.choice(chambers)
chambers.remove(player_chamber)
await ctx.send('The trigger is pulled...')
if player_chamber == 1:
await ctx.send('Oops, you are dead! Better luck next time!')
else:
await ctx.send('`Click! You survived!. You can try again if u dare!')
use this instead @finite abyss
This command is a command just llike the others, there is no need to make it distinct.
im dumb af
wait
ty
wouldnt u have to define player_chamber outside
the command
wouldnt it just reset every time
??
the player_chamber
oh wait yeah
there is no point of removing it from the chamber, it will be redefined before that logic does anything.
and have a separate function choose a random one
wonkey donkey code
im ashamed of my code
lol y so rude
make a dict that stores their userid as the key and the list of chambers they have as the value
import random
from discord.ext import commands
chambers = [0, 0, 0, 0, 0, 1]
@bot.command()
async def chance(ctx):
global chambers
random.shuffle(chambers)
player_chamber = random.choice(chambers)
chambers.remove(player_chamber)
await ctx.send('The trigger is pulled...')
if player_chamber == 1:
await ctx.send('Oops, you are dead! Better luck next time!')
else:
await ctx.send('`Click! You survived!. You can try again if you dare!')
if len(chambers) == 0:
chambers = [0, 0, 0, 0, 0, 1] # Reset the chambers if all have been used
boom, fortnite gamer in the building.
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
wouldnt that use the same list for every user using the bot
would be better to have a per guild or per user one
Isn't that the point.
why else would he remove it from the chamber? Russian roullete is a group game, you go around and eventually one gets shot.
but yeah, per server is probably ideal.
server is called guild in dpy right
yes
ok wait
why global
because otherwise it would reset
and in discord api
every time the command is called
you don’t need a global for that
then whats the solution
Here's a solution
yeah theres a solution
👍
nvm i forgot random.choice() doesnt work on sets
I'm not telling you how to do it, this is merely a demo, do with it as you work.
the code that u sent works just fime
fine
sick
this works
it works but its probably not guild-specific
how can i change the bot text colour?
what do you mean
okay since i can't create folders into my database and neither create dynamically new tables for it i'm gonna discard the idea of using database
time to use the good old json files
Why not?
You can most definitely do this
if you find yourself needing to dynamically create tables, you're almost always doing SQL wrong and need to rethink your model to be more idiomatic.
If you tell us more about what you're doing, we can help you sort out a database model
i'm doing a bot made specially to roleplay
giving it tools for roleplayers and roleplay discord servers
like creating characters, delete characters, edit characters
create template, delete template, edit template
This is pretty common. Why do you need dynamic tables for this?
and also have macros
because on creating character i want to the player being able to use from a template, that can vary a lot
I'm still not seeing a problem
sometimes the template can look like this:
Name:
Age:
Gender:
Alignment:
Strenght:
Weaknesses
or like this:
Name:
Age:
Gender:
Alignment:
Height:
Weight:
Eye Color:
Hair Color:
...
like, many servers can create their own templates from their own multiple minds
and my plan is to make it unique
Oh I see
and really versatile to many servers
I believe postgres has a JSONB type you can use for unstructured data
I really doubt that, JSON as a database is a terrible idea
Would 100% recommend postgres + jsob blob type
can i create folders using json postgres?
What do you need folders for?
to separate macros, template and characters by folders and inside those folders it has each player's id with their own stuff
Why not have a column for storing that information?
E.g a player_id column
that can work, but it would be messy though... But can work
import discord
import discord.ext.commands
from discord.ext.commands.context import Context
from utils import Control
import utils
intents = discord.Intents.default()
bot = discord.ext.commands.Bot(command_prefix=['!'], intents=intents)
class Bot:
TOKEN = utils.PASSWORD
def __init__(self):
Bot.mcr = Control()
Bot.command_await: bool = False
Bot.status_requested: bool = False
def run(self):
bot.run(Bot.TOKEN)
@bot.command(name='help')
async def get_status(self, ctx: Context):
await ctx.send('...')
def launch():
bot_mgr = Bot()
bot_mgr.run()
if __name__ == '__main__':
launch()
I seriously can't figure why the bot doesn't do anything when I type !help
what am I doing wrong?
why not just extend bot instead
what do you mean?
Subclass the bot class
great to know it's a thing
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
INTENTS = discord.Intents.default()
INTENTS.message_content = True
class Bot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix="!",
intents=intents,
)
bot = Bot()
@bot.command(name="help")
async def get_status(ctx: commands.Context) -> None:
...
if I want to have the bot handle commands asynchronously, meaning not blocking, what should I do? Because if one command is in execution another command won't execute until the one before finishes
it already is asynchronous
intents is not defined 🤠
import discord
import discord.ext.commands
import discord.ext.commands as commands
import utils
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready() -> None:
print(f'Logged in as {bot.user.name}')
@bot.command(name='test')
async def test(ctx: commands.Context) -> None:
await ctx.send('test')
if __name__ == '__main__':
bot.run(utils.PASSWORD)
I'm trying to write a bot as simple as that and it literally doesn't output anything when typing !test. I don't know what causes that, can anyone help me please?
You dont have the message_content intent
you should have a warning about that in your terminal-
2023-05-19 04:23:37 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.```
exactly
right. I'll read about it then. Thanks
works like a charm thanks!
i included this in my example too btw
I missed that, my bad
@commands.hybrid_command(name='img', description='High quality images of the ships.')
async def img(self, ctx: commands.Context, ship: str):
s_obj = process.extractOne(ship, sql_ship_obj())
ship_embed_title = f"{customemoji(ctx, s_obj['rarity'])} {s_obj['name']}"
col = int(s_obj['colour'], 16)
embed = discord.Embed(
title=ship_embed_title,
colour=col)
embed.set_image(url=get_ship_image(s_obj['number']))
await ctx.send(embed=embed)
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/opt/homebrew/lib/python3.10/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: object of type 'int' has no len()```
Not exactly sure what i need to fix with this. The issue seems to not be with the code cause the traceback is saying theres an error happening with rapidfuzz process. Background is that it gets all from a db table and i need it to make a match with the given argument. after that everything is based off of that matched result.
How can i add slash commands to cogs?
Yes
!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.
Is that the entire traceback
not completely
let me get it
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "<blah file path>/Dev-Bot/cogs/img.py", line 76, in img
s_obj = process.extractOne(ship, sql_ship_obj())
File "process_cpp.pyx", line 694, in rapidfuzz.process_cpp.extractOne
File "process_cpp.pyx", line 450, in rapidfuzz.process_cpp.extractOne_list
File "process_cpp.pyx", line 360, in rapidfuzz.process_cpp.extractOne_list_f64
File "utils_cpp.pyx", line 44, in rapidfuzz.utils_cpp.default_process_capi
File "cpp_common.pxd", line 331, in cpp_common.conv_sequence
File "cpp_common.pxd", line 301, in cpp_common.hash_sequence
TypeError: object of type 'int' has no len()```
anyone?
this @timid spade
i just responded to you
It's already answered
you put the decorator on a command in your cog class
What does sql_ship_obj return
pretty much an entire sql table
It looks like it returned an int
yea im having a brain fart rn
right?
Add self as the first parameter
Do you have any suggestions of what to change?
The type of thing that the sql_ship_object returns
Looking at the rapidfuzz package you're using, it seems like the second argument of the extractOne method should be a list
Or sequence, whatever
whats wrong with this code it says interaction failed and not creating an embed```@bot.command()
async def verify(ctx):
button = Button(label="Verify", style=discord.ButtonStyle.green, emoji=":white_check_mark:")
view = View()
view.add_item(button)
await ctx.send("Please Verify", view=view)
async def button_callback(interaction):
role = discord.object(1108567412594458634)
user = interaction.user
await user.add_roles(role)
await ctx.reply('You are now Verifed!', mention_author=True)
button.callback = button_callback```
i think it returns it as list indices
You did not set a callback for the button
how do i do that
Set the button.callback attribute to your callback
found the issue i think. was returning the rows but now i got another error 🫠
"tuple indices must be integers or slices, not string"
!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.
are you saying post traceback?
The traceback of the tuple indices must be integers or slices, not string you just sent
Or is it not an error
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "<file path>/Dev-Bot/cogs/img.py", line 79, in img
ship_embed_title = f"{customemoji(ctx, s_obj['rarity'])} {s_obj['name']}"
TypeError: tuple indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/opt/homebrew/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/opt/homebrew/lib/python3.10/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: tuple indices must be integers or slices, not str```
Well, isn't it obvious
yea i ran into this issue before and dont know a way around
!e
a_tuple = ("Meow",)
print(a_tuple[0]) # correct
print(a_tuple["uwu"]) # incorrect
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Meow
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 4, in <module>
004 | print(a_tuple["uwu"]) # incorrect
005 | ~~~~~~~^^^^^^^
006 | TypeError: tuple indices must be integers or slices, not str
You have to get an item from a tuple by the item's index
!e
code
@compact raven #bot-commands
Mb
you dont see slash commands when you run the default help command? right?
no
() on the end
Because you set callback in the callback itself, but for god's sake stop setting them like this
If you don't want to create class for each view create universal view implementation like this one https://github.com/Exenifix/disnake-bot-template-postgres/blob/master/utils/views.py
also add a @commands.guild_only check because your command will fail in other servers or in dms
mmmmm python generics
Yea I use those views in many cases
Not applicable for persistent views and views that are meant to be interacted with more than once tho
i know it's possible to acknowledge a menu interaction without sending a message i forgot how
or don't use views at all
disnake epic moment
snipy rewrite leaf in hikari???
never used hikari
and
Well I could try but I need to finish first a pr for Pokelore
lmao
disnake moment pt 2:
if the function takes an interaction object he can type hint it with disnake.GuildCommandInteraction
that's weird
Leaf & bobux collab
not at all
i am not collaborating with a bot named bobux
💀
they parse slash commmands arguments and if there's GuildCommandOnly they set that attribute for the slash command
ik coz i cried for a pr regarding type hints
yes that is weird
what do arguments have to do with checking if a command can be ran in private messages
@glad cradle leaf or bobux??!2?
mhm idk if I'm able to explain well but I'll try
leasbobux
🧐
@commands.guild_only works too in disnake but when you try to access interaction's attributes that are available only for certain type of interaction classes (disnake interaction classes moment) you'll get a warning from pyright: attributes that may be not available are typehinted as Optional
so using the decorator works but doesn't fix your type errors now if you use GuildCommandInteraction disnake will make your slash command guild only and you won't even have typing warnings
epic
yes you could use @commands.guild_only and GuildCommandInteraction but heh, imagine doing it for all your commands
yes but the interaction could come from DMs
ApplicationCommandInteraction type is any interaction coming from application command invokations
so it could come from guilds, DMs etc..
everything in disnake makes sense except things that weren't rewrited
disnake supremacy
is there a disnake hybrid commands library
also idk if you know how great the stateless components thing is
yes i hate view states
hybrid commands, interactions and views are the worst things in discord.py
no but you can do it easily ig, using some hacks
Wtf you told me you were going to raw dog it
no that's for my other bot
I think ur a coward
I support
once i figure out how rest api works
interactions and application commands are implemented really well in disnake with the interaction types subclasses
also soon™ disnake-ext-components will reach it's stable version
it's an extension to manage stateless components
to not cry listening for components events, checking custom ids, parsing them etc etc
discord sucks i think we should switch to revolt.
why what
why two ui classes
because one is used for components coming from the API, they're components that you haven't created, and the other is used to manage a components from your perspective
makes sense ™
yeah but you could at least rename them to be different or merge them
RawTextInput or TextInputComponent
yes
mhm no
because raw things in disnake are, basically, payloads coming from the Api and they're used mainly for events
TextInput is an object not a dict nor a payload
there's already APISlashCommand

self-bots are against this server's rules
ah sorry
me when i saw good at coding
it's the same thing as discord.Button and discord.ui.Button, the second class derives from the first one, with a callback and simpler constructor. the ui class is to "create" those components while the other one is ready only data from the API
How can i make a context menu command in a Cog?
what are self-bots?
The question regarding "self bots" has come up here and there, and we'd like to make our stance clear:
Discord's API provides a separate type of user account dedicated to automation, called a bot a...
is it possible to trigger a modal through on_message?
No
You can send a message with a button, button can
it's actually good you need to interact with something in order to open a modal
imagine spamming modals to someone lol
sounds fun
Hi, how about replying to the user from on_message?
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Thank you
my bot is responding to every command 2 times
i dont get it why
do you have an on_message listener?
yes i have it in my code
don't call process_commands in it
^
sorry but what is a process_commands here?
oh
ok nvm
i made this listener one a while ago so didnt saw it
i dont even know why i added it there
okay its fixed, thanks @vocal snow
i got this weird error in my warning system
my code is:
Seems like you've never defined the warnings custom bot variable
How is that weird
Considering your code is copied off https://github.com/alphascriptyt/Discord_Rewrite_Tutorials/blob/master/episodes/episode-12.py
You should watch their tutorial again and pay more attention to it
i watched it
all
episodes/episode-12.py line 8
bot.warnings = {} # guild_id : {member_id: [count, [(admin_id, reason)]]}```
so what should i do
im new to python
- Learn Python, at least the basics - discord.py is not meant for beginners, even less for new people
- Copy that line in your code, just like the tutorial?
inside a function?
Just like the turorial????

