#discord-bots
1 messages Β· Page 339 of 1
!e def foo(x): ...
foo()
@shrewd apex :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | foo()
004 | TypeError: foo() missing 1 required positional argument: 'x'
interaction you don't need you're not even using it as for self ur getting .values or some data from it how idk
this?
yes
lmao u have no idea what ur code is doing
im so confused
also idk why u need that # discriminators are not even a thing anymore
if i remove self, it will warn me that its not defined
yes
so do i need to change this:
option_index = int(self.values[0].split('#')[-1]) - 1
selected_data = self.data[option_index]```
well u need to access values whatever that is idk as for data u can just open the json file in the function
in ExpandDropdown
self.data is defined as "data"
@shrewd apex am i supposed to be able to call send_updated()
which is the code ur using the Select or the above
Select one seems fine but u need to attach it to a view and send a message
i copy pasted the callback
yeah no it doesn't work that way
im trying to
u need to use it as it is
the send_updated() is supposed to make a message
that won't work
why not
how can i call this then to let the function know i want to send a message
were just going round in circles u obviously don't know basic python anything i do needs to be spoonfed
if u just want to send a simple message remove all the parameters from send_updated and remove embed and then create a view instance and pass it to the send method also the view instance needs the data object which u loaded from the json file
i know thres an extension to like use the terminal but in the chat, do you know what its called
@shrewd apex
like the eval command in python bot?
or do you mean like accessing the actual underlying terminal of the PC running the bot?
well jishaku has one
thats the name
but restricted to owner only
as an alias yeah
thanks
np
also
my bot wont respond to ping
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
prefix = "!"
bot = commands.Bot(command_prefix=prefix, intents=intents)
if __name__ == '__main__':
bot.load_extension('jishaku')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
all intents are on
and i have bot.run also
@shrewd apex
enable message_content intent
not dashboard in the code btw
u can do intents=discord.Intents.all()
oh right
anyone got recommendations on what host to use for canada idk anything abt hosting
Hey guys, i'm having problem with a cogs, that's the error:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ctfstart' raised an error: ModuleNotFoundError: No module named 'discord_slash' ```
(i've already installed the module)
discord_slash and whatever tutorial you're following are obsolete
discord.py natively supports application commands
oh ok
yo pep what host do u recommend
where can i found the documentation?
What are you gonna be hosting on it
im making a public bot so it can be in multiple servers, i want it on 24/7
DigitalOcean, Linode are the best vps hosting (for serius project) for starting contabo is good
Usually people use path network's for discord bot's -- From what I've seen, Low-latency & high performance.
If you want to make it big you should host the bot on different shards though.
my bot is pretty big too over 3k lines of code so idk what is good for soemthing that big
3K Lines in your main file? What's the majority of code taking that up?
how much should i have
I can't give you a definite answer because it depends, I would seperate my files up more though if possible
wtf?
Show the code
(i'm porting the code, from slash_commands to discord.app_command)
(ignore options)
Only the name for using slash command
the documentation's so bad
it doesn't want the argument "name"
BUT:
I would figure out another way to call to the decorator
I'm actualy watching: commands.command
!rule money
In this code, how could i delete the CREATED webhook only because this code will just delete all of the webhooks in the current channel, which makes sense, but how can i extract the right webhook?
Does anyone know the fix for SSL certificate error in VS Code venv python on macos?
It'll be a bit convoluted but pretty simple. You can get all the webhooks in the channel with GuildChannel.webhooks. You'll then want to sort through those webhooks, find the most recent (You can get the value with Webhook.created_at) and then delete it
Unless somebody has some easier solution to offer
Hint: use the builtin sorted method to sort the created_at values
is on_webhook_update really a thing?
Oh, it only returns a channel
I was hoping it'd return a message.
Can't you just do on_message event and listen for things like webhooks?
Coz I'm thinking, just log message ID's
it's a webhook, but still a message.
There's no guarantee the webhook will send a message though, or a message immediately after they are added
I think I need to read more than a singular message lol
Anyway. I've yeeted my yeet into the wild. I'm sure someone can figure it out.
!paste
did render get any updates to not be able to host discord bots with uptimerobot anymore?
Maybe?
You're using a workaround to host your bot, so I wouldn't be surprised if they patched it
A proper VPS is as low as $4 a month
I mean given that they have a link to webpage generated by the bot, how would they technically patch it?
who knows
Hmm alr
how does this check if the webhook is okay or not? or in other words how do you know it's created with malicious intention or not
I think the one im using is like 10/month but i got extra features to make it buff
It doesn't, but 
Idk what the user is trying to do.
so i cant really offer my 2 terrible cents worth of thoughts
maybe 1 cent. it's low value right now
webhooks are integrations (as far as i know considering discord calls it one) and you should be able to use on_integration_create to get an Integration object but i tried it and couldn't get the event to trigger when making a webhook for the server or a channel, so im not sure
ive been watching this tutorial on how to host my bot using digital ocean, how come it says no such file or directory
https://www.pythondiscord.com/pages/guides/python-guides/fix-ssl-certificate/
I used this to fix my SSL certificate issue, but its on the latest version
Issue: [SSL: CERTIFICATE_VERIFY_FAILED]
I am running a bot from Visual studio, can somone help me
A guide on fixing verification of an SSL certificate.
i have a file called main.py and my botname is bullshark so idk
show you're entire traceback not a screenshot of one line
thats literally all it says
python3: can't open file '/root/main.py': [Errno 2] No such file or directory
that is not the same thing you screenshotted
hey again yall...
ok, so im FINALLY getting back into coding again, and im trying to do a sort of simple-ish slash command to have a user provide 2 string values, and have the first value to remove certain characters,
value_one.replace(" ", "-").replace("'", "").replace(":", "-")
then i have it to basically replace all spaces as -
and after all that, it make the new value processed_value and is put in places in the final_value spot
final_value = f"{processed_value}.{value_two}"
so for example, if i do
/values [The Mug: My Coffee's Burning] [CAFFEINE]
it would reply with
The-Mug-My-Coffees-Burning.CAFFEINE
im fairly new to slash commands, but i do dabble a LITTLE in the old prefix commands.
if anyone can give pointers this late at night, please lemi know, thanks!
@client.tree.command()
@app_commands.describe(
value_one='Gime a value',
value_two='second value',
)
async def values(interaction: discord.Interaction, value_one: str, value_two: str):
processed_value = title.replace(" ", "-").replace("'", "").replace(":", "-") # Replace any spaces, or other special characters
processed_value = re.sub(r'\-+', '-', processed_value) # Replace multiple "-" with single "-"
final_value = f"{processed_value}.{value_two}" # Value produced by processing
await interaction.response.send_message(final_value)
What i have so far :/
if you wanna know why its a little messy, its cause im trying to convert this from prefixes (old commands) to new slash
What problem are you having?
well, when using this exact command, i get an error with re.sub
... and since it was a prefix command last, the entire system kinda changes... :/
What's the error?
one sec
discord.app_commands.errors.CommandInvokeError: Command 'values' raised an exception: NameError: name 're' is not defined
@vocal snow
oh, ffs
so my command works just fine
actually dead af...
so sorry to bother yall
π«
brain actually dead.
look, ive been up for 20 hours, so brain at low function
Without using client how do i get a guild by ID?
Currently I'm using guild = self.client.get_guild(int(profiles['server_profile'].server_id)) but I want to change it from this
is there an inbuilt way?
what's the reason for changing it
Trying to clean up my code and fix it up a bit and I want to change the way my cogs are loaded
well there is no other way to get a guild by its ID
so I have to pass my bot/client to the cog
cool
But interaction/context objects have the client object so I am not sure why that's necessary
You do have to. Cogs take no arguments to their constructor, unless you specify otherwise by overwriting __init__.
What does get passed bot is an extension's setup function
sqlite always confuses me with json stuff
doing some testing rn but cant seem to get this to work
so I've tried running these two queries but always get a sqlite3.OperationalError: malformed JSON
UPDATE tbl SET data = json_insert(data, ?, ?) WHERE id = ?;
params = ('$.newkey', '{"test": "test"}', '1')
UPDATE tbl SET data = json_insert(data, ?, ?) WHERE id = ?;
params = ('$.newkey', '"newvalue"', '1')
best to ask in #databases
another question,
so, lets say i want to have my bot DM me if someone used a command.
user = await client.fetch_user(929950499787145348)
await user.send(f"At {datetime.now()} {ctx.author.id} made a value: "+final_value)
i get an error with ctx not defined, i feel like this is cause of the interaction system, instead of command based dections...
any work arounds?
the discord ID, being mine of course :>
how come in vscode, when i commit the file to my github it doesnt even work?
!d discord.Interaction.user
The user or member that sent the interaction.
@dusk shadow ^^
ahhhh, got it, thank uu!
did u push?
yeah it js didnt do anything
oh im slow mb, idk why its pushing to a whole other repository
π mb
change ur remote
ik
Hello, i try to make a button on my command but this don't work i get an error
@commands.hybrid_command(name = "ticket-panel", description = "Create a ticket panel")
@commands.has_permissions(administrator = True)
@commands.guild_only()
async def ticket_panel(self, ctx: commands.Context):
embed = discord.Embed(title="Ticket Panel", description="Cliquez sur le bouton ci-dessous pour crΓ©er un nouveau ticket.")
components = [Button(style=ButtonStyle.green, label="Create Ticket", custom_id="create_ticket_button")]
await ctx.send(embed=embed, components=[components])```
```shell
2024-01-31 17:42:06 ERROR discord.ext.commands.bot Ignoring exception in command ticket-panel
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/cogs/ticket.py", line 15, in ticket_panel
components = [Button(style=ButtonStyle.green, label="Create Ticket", custom_id="create_ticket_button")]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Button.__init__() got an unexpected keyword argument 'style'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ticket-panel' raised an exception: TypeError: Button.__init__() got an unexpected keyword argument 'style'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/hybrid.py", line 438, in _invoke_with_namespace
value = await self._do_call(ctx, ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'ticket-panel' raised an exception: TypeError: Button.__init__() got an unexpected keyword argument 'style'```
how do i delete a remote cause it keeps saying rep not found cause its trying to find my old rep that i deleted cause ion need it
where you import Button from?
from discord.components import Button, ButtonStyle
git remote remove <remote_name>
ty
most likely cause you are nesting a list inside a list again
but does even discord.py allow components kwarg
Ok so its just components=components ?
technically yes
ok let me try
but if thats discord.py it wont work
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
A hands-on guide to Discord.py
i have already try in my cog but i get error
and simple example on how to
I get this error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/ticket.py", line 18, in callback
if channel.name == f"ticket-{ctx.author.name}" or channel.name == f"claimed-{ctx.author.name}":
^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'```
But i don't use interaction, i use ctx: commands.Context
bruh i'm lost π¦
whats a big change about getting interaction in button callback intead of contexT?
i use that in a cog, and i'm lost with interaction in a cog
how is that
this is my entire code
just explain what you dont understand
How use interaction in a cog, because in everything i have look for understand cog i have never see anyone use interaction
Its the first time i try to use components, i know how to use Interaction in the main file, but in a cog idk if its the same or not
just create a View subclass and handle the components in there like in an example i sent
ok my old code work with everything of ctx replaced with interaction
I just need to found how to make persistent bouton
Its the last things i need to found for my ticket system work
its in the examples folder too
A hands-on guide to Discord.py
Can someone please explain regarding the custom_id of buttons, like there are 3 buttons, so how do I get the id of the 3 buttons seperately
just acess the custom_id property of each button individually?
Can u provide an example?
you set the custom ID yourself
so you should know what it is
How i made a Dynamic id he get my custom id look like "claim_ticket_button" all custom id from ticket finish by _ticket_button the only thing that changes its the first word
Because everything i read he get only an id
like 123456789
when i commit, it updates in the repo but when i run the bot the changes dont apply
Is the response for a button click ctx or interaction?
with open('data.json', encoding='utf-8') as f:
data = json.load(f)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is ready")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(str(e))
class ExpandDropdown(discord.ui.Select):
def __init__(self, data):
options = [
discord.SelectOption(label=f"Expand #{i+1}") for i in range(len(data))
]
super().__init__(placeholder="Learn more...", options=options)
self.data = data
async def callback(self, interaction: discord.Interaction):
option_index = int(self.values[0].split('#')[-1]) - 1
selected_data = self.data[option_index]
embed = discord.Embed(
title=f"{selected_data['title']}",
description=f"{selected_data['title_expanded']}\n\n{selected_data['content']}",
color=0xFFFFFF
)
await interaction.response.send_message(embed=embed, ephemeral=True)```
there is an issue in this code for some reason, it doesn't print it out but i get this interaction has failed after like 3-5 refreshes
i need to paste the code tho
shitty
Is pycord or discord.py used more?
discord.py by a ton
interaction
and the button object itself
ohh, i was using ctx, thnx
I'm always lost with persistent view π
i don't understand how to do for my ticket system
what... you just need to use views as you do normally and call a method on Bot's setup hook
ignore the Dynamic thing
!d discord.ext.commands.Bot.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
I need to add that in my setup hook ?
yeah
ignore the other class of the example
that example shows 2 different things in 1 example, it doesn't make sense
they both achieve the same thing
If i put that this work ?
bot.add_view(TicketCog(bot))
in your case using the former is ok
no
view must be a view not a cog
wait first i have a question
are the views for a single message that is created once or are they used in response messages for commands?
I have a view used on the Ticket Panel where you have the button Create Ticket
In the ticket you have 2 views Close Ticket and Claim Ticket
The Close Ticket after used change for Delete Ticket
then nevermind you need the Dynamic thing approach, ignore everything in that example about the Persistent view
so the first class
π€«π§πΌ
It's normal
how often do the disconnects happen
uhhh
every 15 minutes??
i didnt know that i disconnected
how are you hosting it
is it consistently every 15 minutes
no it varies
is disabling sharding a solution
Do you need sharding in the first place?
no its auto enabled no?
no it isnt
its not enabled by default
if you didnt enable it, it won't be enabled.
hence Shard ID None has connected to Gateway?
Shard ID None
why does it disconnect then π
i dont use logging
then start
@final iron no sharding error apparenlty
it just doesn't wanna load after some time idk why tho
yea
idk for disconnecting but there is none
We went over this. It has nothing to do with sharding.
okay so what could be the issue
Already went through this. Itβs impossible to say without logs
Show your updated code
You didnβt set up the logging level properly
i probably didnt
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
if __name__ == "__main__":
bot.run("token", log_handler=handler)```
Go over the link I sent please
Go over the link.
which one do u want
debug or info
nvm that was a stupid question
@final iron caught some logs
it seems like the bot would "time out" if no one used the interaction
and in the console, when requested to open data.json it should print "loaded", however it didnt
"This interaction didn't respond"
these logs show nothing out of the ordinary
look at this
i can send the code if u need it
yes that would be most helpful
I see. That's quite a lot of code, and what I assume is happening here is that a logging entry from asyncio is being eaten, because you only have the discord logger enabled, and no errors of what you do would get propagated to them.
Could you please enable the root logger, and send the resulting logs? (do not enable debug logs since that's just gonna fill your console up with bullshit.)
handler = logging.handlers.RotatingFileHandler(
filename='discord.log',
encoding='utf-8',
maxBytes=32 * 1024 * 1024, # 32 MiB
backupCount=5, # Rotate through 5 files
)
if __name__ == "__main__":
bot.run("token", log_handler=handler, root_logger=True)
π
This is my issue, can anyone help
so, do i remove this?
dt_fmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
handler.setFormatter(formatter)
logger.addHandler(handler)```
im assuming yes
the addHandler can be omitted
but the formatter part, sure, keep it, unless you want to keep discord.py's default formatter. (wont affect anything useful either way)
this get's removed too right
yeah, that only brings up useless stuff
okay gimme a sec
this seems pretty useless
i don't know if the error occurs rn tho so gimme a sec
yea as i said it needs to time out after some time
idk how it happens or when
you mean the fact that a button(view*) stops functioning after the default timeout of 180 seconds?
yeah
wait 1 more minute
I mean... https://paste.pythondiscord.com/ELAQ#1L119-L119 super().__init__(timeout=None)
it will stop working after a restart, though
..... π
was it really that simple.
this whole code is a big mess though, I would suggest organizing things out. massive while true with... a lot of... stuff π₯΄
yeah umm
rule #1 of coding
if it works dont touch it
rule #3 of coding: (maybe) ignore rule #2
rule #4: error- infinite cycle
hm
wrong init
see this carefully-er
or nvm lmao yeah
thanks π
you should add this to your code:
no problem π
LMAOOO
@pale zenith thanks for telling me how to change the timeout
i knew it timed out π
i will start adding this to my coding projects (even if it's perfectly readable, documented and fairly organized but shhh)

@pale zenith same π
Which problem do you facing in slash cmd ?
iv fixed it by now, forgot to sync
well mates i have i question , i am tryna make a bot for code quiz like a competitive and score sharable bot but cant understand how can i get question for quizz the way i want (in subtopics and different difficulty level ) what is the best way you think ?
store it in a json?
and then, send the question you want to the user
works but as a user start using it questions end up getting same and if i use api there is also the problem of repeat questions
what do you want to do exactly?
Send an infinite amount of questions?
i mean not infinte but atleast not like just same 10-20 question repeating
yeah I see
and as a user you dont want like repeating question in a quiz beats the whole purpose of quiz
of course
what did you think about when you said api?
like generating questions?
well im tryna find a api which works like my criteria but ig feels like im dream real high so have to go down on it , like there is quiz api there is barely for programming quiz + just for normal topics like html python like very lil catagorys
I think in this case, the best you could do is to create yourself a lot of questions
because, if you use an ai to generate it, the questions won't have any sense
If you could find an api, it could work but I don't have any in mind rn
if you want to use it with a discord bot, I don't think you must create an api
you can have your questions locally
like how ?
a local json file, or in a database
understand
lets se how i do , well is it better to have mulity choise question or a single word text answer
as you prefer, I thought first about a multiple choice question, but both are pretty easy to do
well yes mutl question easy to make as buttons and event but will take more space / single word answers will take less space but gives user a chance to make chaotic text and might create confict in comparing answer
yes
the easiest is multiple choices
you could do strings comparisons if you expect for string answers
well what is the best way of storing question in way that amount of space they take wont matter
You store only ascii characters, so even if you have a huge amount of questions, your file won't exceed some MB
which is quite reasonable I think
or, if you do it with a database, it will be a little bigger but you won't have to load it in ram
hmmm @vestal acorn what if i give them id number and as they are being answered by the user store the id number and try not to repeat them this way
I would work I think
fetch the list of questions from ur json file and store it locally in a variable. Use random to pick a random question from the list. After each question, remove the previously sent question from the list.
understand
but each time the user restarts the quizz, every question could be sent again
I mean yeah if they do the same quiz multiple times, thats possible with any quiz. Youll just need to make sure you have enough amount of questions that the chance of a question repeating is very low
yes
for whatever reason, my bot's commands are not working, they are showing up in the server's integrations tab but not showing up when trying to use them, is there something I did wrong?
sounds like a permissions thing, do you have default permissions set
how can you make your bot check if a users message contains a sticker
!d discord.Message.stickers
A list of sticker items given to the message.
New in version 1.6.
thank u
Does interaction.followup not have a send_modal? D:
it can only be in response
I figured as much
So I have to do something else :(
:D it's okay. I think this solution is better anyway
More intuitive for the end user!
@shrewd apex :D
π
feel like that would be too many fields for mobile embed view
each would occupy a line
Do you have a proposed alternative?
Something I could do to improve?
Because I need to be able to send multiple modals and I dont want individual commands.
It needs to be simple and straight forward.
@shrewd apex
Mobile
maybe some checkbox emoji in one field? some text formatting? like u could have a toggle group asking warn/ban/timeout user
What do you mean by toggle group?
just a gui concept thing it's not anything discord specific
Oh
I mean, I could improve the button text to explain more
Like "Don't Ban User" and "Ban User"
Or "Toggle Ban User"?
@client.tree.command(description='Use this before setting channels.')
@app_commands.checks.has_permissions(administrator=True)
async def setup(ctx):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(
'SELECT settransactionschannel FROM users WHERE guild = ?',
(ctx.guild.id, ))
data = await cursor.fetchone()
if data:
pass
else:
await ctx.response.send_message(f"Set everything up!", ephemeral=True)
await cursor.execute(
'INSERT INTO users (settransactionschannel, setlogschannel, setalertschannel, setgametimechannel, setpickupschannel, setstreamschannel, setfreeagencychannel, setnoticeschannel, setverdictschannel, guild, setdemandchannel) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
(
0,
0,
0,
0,
0,
0,
0,
0,
0,
ctx.guild.id,
0,
))
await db.commit()```
i have this command where when u run it it like setsup the database so that you can set channels, how would i put this in my on_ready so that people dont gotta run it everytime a new set command is added and instead it updates the second the bot is started
how can i disable a button after one click it doesnt work here
you need to edit the old message with the new disabled button
py
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/root/bullshark/main.py", line 100, in on_ready
await cursor.execute(
File "/usr/lib/python3/dist-packages/aiosqlite/cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "/usr/lib/python3/dist-packages/aiosqlite/cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3/dist-packages/aiosqlite/core.py", line 129, in _execute
return await future
^^^^^^^^^^^^
File "/usr/lib/python3/dist-packages/aiosqlite/core.py", line 102, in run
result = function()
^^^^^^^^^^
sqlite3.DatabaseError: database disk image is malformed```
idk what to do i tried so many things
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute(
'CREATE TABLE IF NOT EXISTS users (settransactionschannel STRING, setlogschannel STRING, setalertschannel STRING, setgametimechannel STRING, setpickupschannel STRING, setstreamschannel STRING, setfreeagencychannel STRING, setstatschannel STRING, setnoticeschannel STRING, setverdictschannel STRING, guild INTEGER, setdemandchannel STRING)'
)
await db.commit()
async with aiosqlite.connect("main.db2") as db2:
async with db2.cursor() as cursor:
await cursor.execute(
'CREATE TABLE IF NOT EXISTS users (setrefereerole STRING, setcandidaterole STRING, setcaptainrole STRING, setsuspendedrole STRING, setstreamerrole STRING, guild INTEGER, seteligiblerole STRING, setmanagerrole STRING)'
)
await db2.commit()```
your database is fucked
idk how it was, i fixed it that shit took so lonng
i had to deleted the databases and re add them and push it to github
but like i already did it so idk why it didnt work the first time but it worked now
why would you create a different database just for another table
lolll actually
why not lmao
1 db per table
What is the best package for detecting non-English messages for my Discord bot?
You can just iterate through each letter and see if they are present in the English alphabet
While also excluding symbols and numbers
well, it's not just english that uses the latin alphabet
^
I think I need a package
idk maybe use googletrans or something
You could use str.isascii() to do pretty much what I told before
!pypi langdetect
Not accurate for short messages
obviously messages like that will be missunderstood
Not by using https://github.com/detectlanguage/detectlanguage-python but this one requires an API key and the free version is max 1000 request/per day
(same message '+1 Draft')
how is that polish
Niewiem
ja tez nie
Is this really using Google's language-detection? Because Google shows me this

At least the reliable is True for english
cool
how do i reload my bot with jishaku
howw ould i make a command where i transfer data from a command to a googlr spreadsheet?
When it comes to sharding a discord bot , is it possible to assign certain commands and cogs to a specific shard?
And can I reload specific shards or do I need to reload the entire not still?
I'm hosting my bot with heroku and it's being difficult, the github is connected, but the deploy says it can't identify what default language it's using(what type of code)
You can set it in the settings
and you should have a Procfile I suppose, which you're eventually missing
How would one do that
I found the deploy keys section, I just don't know what to put there
u need to add a procfile iirc and the python package
No idea what any of that means lol, do you mind explaining ?
How do you add a procfile
iirc means "if i remember correctly" fwiw
._. Oh dang I'm not smart when it comes to abbreviations
Lmao
Now it's saying buildpack not compatible with app
Is there any specific way to assign specific commands/cogs to a given server on loadup?
Either using sharding or something else?
I know I can just have a decorator that checks if the guild has permissions based on my database, but it'd be nice if they couldn't even see the command to begin with.
!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), 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) or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu) decorator then this must go below that decorator.
Example...
there is also discord.app_commands.default_permissions so it doesnt appear for users without the perm
@golden portal - Can I update that dynamically? Like lets say originally a guild isnt in the list of IDs, could I update it using a command?
the built in way, no, since its a guild specific commands, you can however just sync an empty tree onto that guild that you removed it from
import discord
import json
from discord.ext import commands
# Import cogs
from cogs.cheetos import Cheetos
from cogs.private_commands import PrivateCommands
from cogs.public_commands import PublicCommands
from cogs.rah import Rah
from cogs.rahlink import RahLink
from cogs.vdfchecker import VDFchecker
from cogs.tickets import RAHTickets
from cogs.chatmoderator import ChatModerator
from cogs.test1 import Test1
from cogs.test2 import Test2
with open("./configs/config.json", "r") as config_file:
config = json.load(config_file)
class MyBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=config['additional']['prefix'],
intents=discord.Intents.all(),
application_id=config['additional']['application_id']
)
self._cogs_to_load = {
#"Cheetos": Cheetos,
#"PrivateCommands": PrivateCommands,
#"PublicCommands": PublicCommands,
#"Rah": Rah,
#"RahLink": RahLink,
#"VDFCHECKER": VDFchecker,
#"RAHTickets": RAHTickets,
#"ChatModerator": ChatModerator
}
self._cogs_to_load['Test2'] = Test2
self._cogs_to_load['Test1'] = Test1
#self._cogs_to_load['RAHTickets'] = RAHTickets
#self._cogs_to_load['ChatModerator'] = ChatModerator
async def on_ready(self):
for guild in self.guilds:
if guild.id == 1203230080512294922:
print(f"Syncing to {guild.name}")
for name, cog_class in self._cogs_to_load.items():
cog_instance = cog_class(bot=self, config=config)
await self.add_cog(cog_instance)
await bot.tree.sync(guild=guild)
print("Bot fully loaded and ready to go!")
# Ensure the script is being run directly, not imported as a module
if __name__ == "__main__":
bot = MyBot()
bot.run(config['tokens']['discord_token'])
Already doing this and it doesnt seem to work properly
although I'm definitely doing something wrong lol
why arent you syncing globally tho
Coz I want to be able to sync specific cogs/commands to specific guilds.
For example "PrivateCommands" in that code i shared are just for me. So why should others see them?
you can just set the cog to be for a specific guild in the extension like so, ```py
guild = discord.Object(1203230080512294922)
await bot.add_cog(cog, guild=guild)
then just `bot.tree.sync(guild=guild)` at the end
why aren't you using extension?
i need help with heroku hosting, says the app isnt compatible with buildpack even thought thier both python
What do you mean? I thought I was lol
you're just using a cog there, people usually coupled with extensions
(the part where it's a specific file with function for setup and teardown)
async def on_ready(self):
for name, cog_class in self._cogs_to_load.items():
cog_instance = cog_class(bot=self, config=config)
await self.add_cog(cog_instance)
await self.tree.sync()
print("Bot fully loaded and ready to go!")
``` All my cogs are in individual files. I'm just loading them here.
Instead of needing the "setup" at the end where it adds the cog it does it here
i know, im just asking why
u could achieve the same with just a list of extensions, but oh well im not gonna go nerdy
This way I can add new features without needing to remove the files
I can also parse things like the config file down to each cog
Instead of each cog needing to load the config
Why open the file many times when 1 is enough?
having to reinvent the wheel isnt really my thing so you do you
Is there a proper way to make a command sleep/wait?
need more elaboration on that, do you just want an asyncio.sleep?
utils/bot.py lines 68 to 78
def auto_setup(self, module_name: str) -> None:
module = importlib.import_module(module_name, None)
sys.modules[module_name] = module
members = inspect.getmembers(
module,
lambda x: inspect.isclass(x) and issubclass(x, commands.Cog) and x.__name__ != "Cog",
)
for member in members:
self.add_cog(member[1](self))
self.log.ok("%s loaded", module_name)```
Load config in a module and import the module in extensions
Or make it bot subclass attribute
how and where do i start making a discord bot
See pinned messages and the channel description
If you have learnt about intermediate and a bit advanced python topics , you can start learning making discord bot from it's docs and examples
is it possible to edit bot's bio using discord.py?
as far as i know you can only set it on developer portal
i need help with heroku hosting, says the app isnt compatible with buildpack even thought thier both python
async def saldo(ctx, user: discord.User = None):
if user is None:
user = ctx.author
user_id = str(user.id)
balance = get_balance(user_id)
embed = discord.Embed(title=f"Perfil de {user.name}", description=f":MoedaGira: Saldo: {balance} Uabos", color=0x00ff00)
embed.set_thumbnail(url=user.avatar.url)
await ctx.send(embed=embed)``` how can i make like the bot reply the image like its on the image?
!d discord.ext.commands.Context.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 [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) referenced by this context.
For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send).
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) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
!d intents
Ask the issue(s) you're facing and we can help you fix them
i need help making a bot
See pinned messages and the channel description, as well as https://discordpy.rtfd.io
I need help with the sb discord ai project if anyone would be willing to help me let me know in a private message
How can I make a bot that automatically assigns a role when someone comes to the server?
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
Listen to the event on_member_join and use the add_roles method on the member to add the role you wish
What is it
import discord
from discord.ext import commands
from PIL import Image
from io import BytesIO
PREFIX = '!'
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
if message.attachments:
for attachment in message.attachments:
if attachment.url.endswith(('.png', '.jpg', '.jpeg', '.gif')):
await process_image(message, attachment)
return
print("Message received:", message.content)
async def process_image(message, attachment):
image_data = await attachment.read()
image = Image.open(BytesIO(image_data))
text = ocr_text_from_image(image)
print("Extracted text:", text)
target_sentence = how many ppl in the earth"
if target_sentence.lower() in text.lower():
await message.channel.send("8billion")
else:
await message.channel.send("No match found.")
def ocr_text_from_image(image):
try:
import pytesseract
return pytesseract.image_to_string(image)
except ImportError:
print("pytesseract library not installed. Install it using 'pip install pytesseract'.")
return ""
bot.run(TOKEN)```
why does this don't work, it's should take the image that the user send it to the channel, then check if it's include the question 'target_sentence = how many people in the earth" then send me the answer which is 8B, if didn't find say i don't know the answer, help please
Missing a "
Oh lol, let me check
Hmm i have it, maybe when i copy it i miss click it and delete it π€
But still not working π
Heya I'm tryna make my bot do some stuff and frankly
I'm lost for ways to try make it work :0
try hitting it
what stuff?
basicly im trying to get it to react to a message as in
you type ?hi and it picks up on that and replys with hi... hru
u then answer and depending on ur answer get a differant responce
if u say good or smthg u get like great have a good day
and if u reply with not so good you get a completely differant answer and dialog
also i want the code to basicly have a shut off time of 1 min so if you dont answer in that time the interaction stops
and i want it to react to the person who origonally did the ?hi
so like a chatbot
yea basicly
chatbot
itll have other functions but mainly yea, as its my first time building a bot so its a way for me to learn how to implament it practicly
might be a bit complicated for a first bot lol
i like to challange myself
You have python experience, right?
long ago and remember little to nothing
Well, as of now I've been learning python for a month and yet to fully understand it. So I recommend you learn more before you jump into bots.
And I know getting chatbots will even further complicate this.
Or just chat-gpt the whole thing
id like to know how to create a countdown timestamp (doesn't have to be timestamp) on discord.py using datetime/timedelta
so you dont want to use discord.utils.format_dt? just a normal countdown? you can do that by getting the difference between current datetime and the end datetime and use timedelta.total_seconds() then calculate it yourself to get hours, minutes and seconds
sure, use the R style for format_dt
much easier, and it's also live, check this out:
<t:1707019080:R>
and how do I flip idk how to put this in a sentence rn, my brain isnt braining
but how do i if it lol
huh?
or should i say calculate the time so
for example if it says in minutes 0 or 1 minute ago it triggers an event
you would simply wait until then with asyncio.sleep
the explanation hasnt clicked yet srry
;-; really man
something wrong?
Yes, there's birds in my chat
its pretty simple ```py
dt = discord.utils.utcnow() + datetime.timedelta(minutes=2)
await ctx.send(f"Send message in {discord.utils.format_dt(dt, style='R')}")
await discord.utils.sleep_until(dt)
await ctx.send('Countdown ended')
No Its just more comfortable using a if statement wasnt expecting that but yh thanks
not everything yields to an if statement. that's why we have other language constructs
but also running a while true and checking the current time wastes clock cycles
no i mean relating to this, time weilding it just feels more comfortable
i apologize
not sure what you mean by "time weilding"
ah dont worry about it, my head is on flames looking all over for timestamp manipulation
where should I learn to start coding discord bots?
I have a decent understanding of python now
wait nvm
thats why i said it doesnt have to be timestamp so i can manipulate it more efficiently
I can't use decorators though or lambda.
sorry but checking time every second or so is less efficient than just a simple asyncio.sleep
Should be some resources in the pins
ok
Assuming Discord Bots will be able to get Join Method soon?
What's the point? All Discord bots have the same join method
makes sence.
welp atleast now ik.
No, i meant like where they can get the data of how a person joined?
Aka invite, and whos invite n stuff like that
Ah, not sure about that then
Because currently they still do not have access to that unless im living under a rock..?
Yeah, im hoping just hoping, they add it.. because it would be kinda nice. But if they don't then thats fine, been like that for 3 years now, we started asking 3 years ago, they still haven't done it π
it is how it is
Is there a clear way to see what guilds my bots in? outside of just listing them using my bot?
like is it on the discord website somewhere?
no
Discord dispatches that information when you connect to the gateway
run a side web server on ur bot and query it as u would query an api π
If I want to use the timeout function to time someone out, do I need to submit a proper datetime or can I use something like "1d"?
the Member.timeout method? have to be a datetime object or a timedelta
someone know yt channel that have good playlist for beginners?
i don't think they'll ever add it, if you want something to track invites you can already by listening to the member join event and check if one of the invites present in the guild had the use count go up by 1
you'll be able to tell who invited a user and how many users a member invited
!d discord.Embed.set_image - you need to use this method to set the image of the embed, not just putting an image URL into the description
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
guys can someone help me, the part of the code isnt being executed i mean the command works but it should send a message that says that i successfully withdrew the coins, but it doesnt
First I'd remove that horrible try/except
Then you'll see errors in the console and it will help you debug your code
sure!
async def banner(self, ctx, member: discord.Member = None):
if not member:
member = ctx.author
elif isinstance(member, int):
member = await self.get_member_by_id(ctx.guild, member)
if not member:
embed = discord.Embed(description="User not found.")
return await ctx.send(embed=embed)
banner = member.banner
if banner:
banner_url = banner.url
embed = discord.Embed()
embed.set_image(url=banner_url)
embed.set_author(name=f"{member.display_name}'s banner", icon_url=member.avatar.url)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description="User does not have a banner.")
await ctx.send(embed=embed)```
Even if the user has banner it says "User does not have a banner." Did they change the way to get someone's banner or?
ohh you were right! now it shows me the error
fixed! Thank you krypton, i really appreciate your help!
property banner```
Returns the userβs banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
^ you'd need to fetch the user with the .fetch_user method of the bot to access their banner (for some unknown reason)
Wow. I've never done something like that π Can you give an quick example?
# spoonfeeding? π
# or "self.bot", depending on how you name it
user = await self.client.fetch_user(member.id)
print(user.banner)
self bot 
no sir 
import discord
from discord.ext import commands
from PIL import Image
from io import BytesIO
PREFIX = '!'
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
if message.attachments:
for attachment in message.attachments:
if attachment.url.endswith(('.png', '.jpg', '.jpeg', '.gif')):
await process_image(message, attachment)
return
print("Message received:", message.content)
async def process_image(message, attachment):
image_data = await attachment.read()
image = Image.open(BytesIO(image_data))
text = ocr_text_from_image(image)
print("Extracted text:", text)
target_sentence = how many ppl in the earth"
if target_sentence.lower() in text.lower():
await message.channel.send("8billion")
else:
await message.channel.send("No match found.")
def ocr_text_from_image(image):
try:
import pytesseract
return pytesseract.image_to_string(image)
except ImportError:
print("pytesseract library not installed. Install it using 'pip install pytesseract'.")
return ""
bot.run(TOKEN)```
why does this don't work, it's should take the image that the user send it to the channel, then check if it's include the question 'target_sentence = how many people in the earth" then send me the answer which is 8B, if didn't find say i don't know the answer, help please
Hi, can anyone tell me the problem with this code? It takes me the names of random people, and it doesn't tell me who moved who when a person is taken to its own
@client.event
async def on_voice_state_update(member, before, after):
mover = None
# Trova l'utente che Γ¨ stato rimosso dalla stanza vocale originale
for member_before in before.channel.members:
if member_before not in after.channel.members:
mover = member_before
break
# Costruisci il messaggio in base a chi ha effettuato lo spostamento
if mover is not None:
# Se mover Γ¨ diverso da None, utilizza il suo display_name
if member != mover:
# Se il membro non Γ¨ il responsabile dello spostamento, allora ha spostato l'altro utente
message = discord.Embed(title="1", description=f"{mover.display_name} ha spostato {member.display_name} dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")
else:
# Altrimenti, considera l'utente stesso come responsabile dello spostamento
message = discord.Embed(title="2", description=f"{member.display_name} ha spostato {mover.display_name} dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")
else:
# Nessun utente rilevato come responsabile dello spostamento, quindi l'utente stesso si Γ¨ spostato
message = discord.Embed(title="3", description=f"{member.display_name} si Γ¨ spostato dalla stanza vocale '{before.channel.name}' alla stanza vocale '{after.channel.name}'")
# Invia il messaggio nel canale specificato
channel = client.get_channel(CHANNEL_ID)
await channel.send(embed=message)
I'm getting this problem which I don't understand why its happening, I want the image to be on the embed but its not. Heres the code: ```
user_id = str(ctx.author.id)
cost = 10
current_balance = get_balance(user_id)
if current_balance < cost:
embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: NΓ£o tens Uabos suficientes para abrir a caixa.", color=0xff0000)
await ctx.reply(embed=embed)
return
case_folder = os.path.join("C:\\Users\\Admin\\Desktop\\bot\\Itens", case)
if not os.path.exists(case_folder):
embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: Caixa nΓ£o encontrada.", color=0xff0000)
await ctx.reply(embed=embed)
return
rarity_folder = random.choice(os.listdir(case_folder))
rarity_path = os.path.join(case_folder, rarity_folder)
if not os.path.isdir(rarity_path):
embed = discord.Embed(title="Erro ao abrir a caixa", description=":x: Pasta de raridade nΓ£o encontrada.", color=0xff0000)
await ctx.reply(embed=embed)
return
item = random.choice(os.listdir(rarity_path))
item_name = os.path.splitext(item)[0]
item_path = os.path.join(rarity_path, item)
# Determine the rarity based on the folder name
rarity = rarity_folder.capitalize()
desguaste = random.uniform(0, 1)
update_balance(user_id, current_balance - cost)
embed = discord.Embed(title="Caixa aberta", description=f"{ctx.author.mention} abriu a caixa `{case}` e obteve `{item_name}` ({rarity}) com desgaste {desguaste:.10f}.", color=0x00ff00)
try:
file = discord.File(item_path, filename=f"{item_name}.png")
embed.set_image(url=f"attachment://{item_name}.png")
await ctx.reply(embed=embed, file=file)
except FileNotFoundError:
embed.set_image(url="attachment://image.png")
await ctx.reply(embed=embed, file=discord.File(item_path, filename="image.png"))```
Hey everyone.
I am currently working on a Discord Bot. I want to bring it to the next level. So if anyone is interested in developing this Project with me. Let me know.
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Issue is, then you would have to do that for every single sever, thats a lot of cpu power. I don't think I wanna do that lmao
not much CPU power, just a lot of incoming events and requests to your database
Discord should just allow us to do it, instead of doing all of that π
Guys
@bot.tree.command(name="count",description="Count 1 To 9")
async def get_orders(interaction: discord.Interaction):
for x in range(9):
await interaction.channel.send(x)
For example , i have an slash command when i trigger it , it count 1 to 9
I want to recieve an error when another command or slash command is triggered when this command is counting from 1 to 9
And have another slash command like :
@bot.tree.command(name="say_hello",description="Send Hello In Chat")
async def say_hello(interaction: discord.Interaction):
await interaction.channel.send("Hello!")
I want to recieve an error when trigger
say_hello
command , while another slash command is working (counting 1 to 9)
How it work?
Can anyone help me?
How do I prevent this code from advertising my own ad in my advertising channel?
Hello, I've created this public bot that can do partnerships and advertising and for some reason people are having issues with this feature of my bot saying that it keeps on advertising their own ad in their own advertising channel so I figured to come here and get some support.
@tasks.loop(seconds=2400)
async def auto_advertise2(self):
async with self.bot.db11.cursor() as cursor:
await cursor.execute("SELECT channel, guild FROM advertise WHERE setup='TRUE' AND auto_advertise='TRUE' ORDER BY RANDOM() DESC LIMIT 40")
channels = await cursor.fetchall()
channel_ids = [channel[0] for channel in channels] # Extract channel ids from the tuples
guild_ids = [guild[1] for guild in channels] # Extract guild ids from the tuples
placeholders = ', '.join('?' for _ in channel_ids) # Create placeholders for the query
await cursor.execute(f"SELECT guild FROM advertise WHERE channel IN ({placeholders})", channel_ids)
guild_id_tuples = await cursor.fetchall()
# Extract guild ids from the tuples and convert to a tuple
guild_ids = tuple(guild_id[0] for guild_id in guild_id_tuples)
async with self.bot.db2.cursor() as cursor:
placeholders = ', '.join('?' for _ in guild_ids) # Create placeholders for the query
await cursor.execute(f"SELECT guild, ad, discord_link FROM ad WHERE guild IN ({placeholders}) ORDER BY RANDOM() DESC LIMIT 40", guild_ids)
ads = await cursor.fetchall()
for i, channel_id in enumerate(channel_ids, start=1):
guild, ad, link = ads[i % len(ads)]
ad = ad.replace("@everyone", "").replace("@here", "")
# Skip if the guild is the same as the current guild
channel = await self.bot.fetch_channel(channel_id)
if channel == channels:
print("Prevented guild from advertising in its own advertising channel")
continue
await channel.send(ad)
await channel.send(link)```
DB 11 SQL structure:
await cursor.execute("CREATE TABLE IF NOT EXISTS advertise (guild INTEGER, channel INTEGER, setup STRING, auto_advertise STRING)")
DB 2 SQL Structure:
await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING, banner1 STRING, banner2 STRING, discord_link STRING)")
i dont know what this means cus i dont have a file named <stdin>
those are my files
looks like an issue in vs code, it seems youre in the python repl mode
type in
exit()
in my terminal?
yeah where it said that error
line 2 and 3 are what i got when i tried to run the file
that should get you out of there, try pressing crlt c?
ive made a ton of bots before not sure where i went wrong
are yoy on windows?
yeah
this is just an issue with vs code, maybe just restart vs code
sorry for sending ss of the code lol
class EmbarkBot(commands.bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self) -> None:
self.add_view(PersistentCloseButton())
self.add_view(PersistentConfirmation())
self.add_view(PersistentTicket())
bot = EmbarkBot()```
ah idk about that, well at least you got your vs code fixed now
I believe it's commands.Bot?
yep
does anyone know why this only dumps the first part of a text?:
hello
pressing a button registers that you pressed a button but it doesnt record you pressed the button
so the board still thinks it's empty when you make a move
and when the board fills and you cant play any more, it just times out
uhh
this doesnt make any sense lol
ok so how it works is on a 3x3 grid
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
set out like this
I got that.
So is your issue that it's detecting you're pressing ANY button? and not the ones related to TTT?
when i press a button, it responds appropriately by changing the label from an invisible character to the player that clicked it
but it doesnt make note of that on the board
it just says "interaction already responded or smth"
oh
Just edit the message.
hold up
await interaction.response.edit_message(embed=embed, view=self) is what I do.
# terminal
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before```
!paste
https://paste.pythondiscord.com/VZ4A this is what I'm working on at the moment
i alr put a link but i'll put it again: https://paste.pythondiscord.com/BFXQ
So the "message_edit" basically resets the interaction
im currently working on trying to send modals XD
so the print_board() thing shows the board and the exception
My code is different to yours but has the same concept
allow the user to click many buttons on the same interaction
yeah i know how to do that, i just dont get how pressing a button doesnt put anything on the board π
yes
another test
# terminal
axololly is playing against altololly in Tic-Tac-Toe.
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Exception: This interaction has already been responded to before```
it's not done. Still doing the modals.
full error py Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task await item.callback(interaction) File "c:\Users\user\OneDrive\Desktop\My mum made me do this\Python\Discord\some games\tictactoe.py", line 184, in four await self.input_move(interaction, button, 4) File "c:\Users\user\OneDrive\Desktop\My mum made me do this\Python\Discord\some games\tictactoe.py", line 167, in input_move await interaction.response.defer() File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 639, in defer raise InteractionResponded(self._parent) discord.errors.InteractionResponded: This interaction has already been responded to before
Alright i'll debug it now.
Also, it's all 1 script for sharing purposes right?
@viscid hornet i'm going to make some changes to improve it as well, do you mind?
its alr i found out i responded twice then i didnt assign anything to the square
so thats those 2 problems solved. i just need to fix the logic for tictactoe
Something like that's happening as well
like checking when theres a win
I'm going to make some modifications to the code, improve it, make it easier for users to use etc.
f"Probably a good idea to find new friends.", lol i love all these things
"go touch some grass ποΈ" π
not you, dingus
this is weird. why are you doing this
If you remove the self.players from your code, you can do stuff like this. Idk if it's better, but it'd make for cooler variable names.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
challenger and victim is insane π
XD
i dont even use player and opponent
how do i go about a system to do this? ```py
1 2 3
4 5 6
7 8 9
[(0, 0), (0, 1), (0, 2)]
[(1, 0), (1, 1), (1, 2)]
[(2, 0), (2, 1), (2, 2)]```
i want (0, 0) to be 1, (0, 1) to be 2, etc
Why?
Also it looks like a list of tuples.
So just print out the list number and add 1
placing the pieces in the board
each tuple just represents a pair of list indices ```
(x, y) where board[y][x] is valid
so you can have board[1][0] which corresponds to the 1st item in the 2nd list
but you cant have board[34][-29] because thats not a valid index
Can someone help me? 
Specifies if the user is a bot account.
Which doesn't have a pool attribute
!d discord.Interaction.client - maybe you're looking for this attribute instead?
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot) are all subclasses of client.
ohh may i use interaction.client?
ahh yea, sure let me try
Any examples of quiz bots that I can use for deciding how to handle multiple rounds of a quiz? I'm at the point where my bot can generate one quiz question or fetch data for multiple questions, but not sure what the best way to handle responses and listening for messages across multiple questions would be
i changed that, now it says something with bot has no attribute "client"
WARNING discord.gateway Can't keep up, shard ID None websocket is 12.6s behind. what does this mean
import os
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.all()
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('Logged in')
async def setup():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await client.load_extension(f'cogs.{filename[:-3]}')
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.all()
client = commands.Bot(command_prefix='!', intents=intents)
class ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(client):
client.add_cog(ping(client))```
Can anyone help me with this?
[2024-02-05 18:52:57] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
You're blocking somewhere
is there anyway to see where
and how to stop blocking
if you paste all of your code we could take a look
!paste allows for uploading multiple files
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Or a GitHub repository if you've got one
only thing blocking here is redis
and maybe better_profanity but i'd have to read src code for that
im using async redis though
oh is it this,
host='redis-11943.c56.east-us.azure.cloud.redislabs.com',
port=11943,
password='
')
```
I am trying to implement discord bot using Chat GPT interface
Here's the Code
# App id 1203563046262538250
# public key ec4c2301877d7edca03a8e6a
import discord
import os
import openai
# client = OpenAI()
openai.api_key = os.getenv("GPT_KEY")
token = os.getenv("SECRET_KEY")
# rest of the code remains the same
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
if self.user != message.author:
bot_mentioned = any(user.id == self.user.id for user in message.mentions)
if bot_mentioned:
response = openai.completions.create(. #<--------Possible ERROR
model="gpt-3.5-turbo-instruct-0914",
prompt=message.content,
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
channel = message.channel
messageToSend = response.choices[0].text
await channel.send('Hello I am Chitti Boom!')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run(token)
I was somehow able to locate the problem to some extent to response = openai.completions.create line but not sure about this
My discord bot is not responding to my messages
I need help with cogs
I added everything I need (I think)
But when I run my main file nothing else works
none of my cogs work
- did u load the cogs?
- verify the cog paths when loading?
- make sure your cog loading is async following changes in dpy 2.0
- if its slash command, did u sync?
response = openai.completions.create(. you have some random dot . at the end of this line
inb4 this was generated code
is
broken?
Like move_members
I have all perms in my test server, but I run the command that wants that perm, it says I don't have that perm. Make me wonder if its bugged or im doing something wrong?
Same with mute_members and deafen_members
The 3 permissions are just not correct? Like I have all permissions, but still says I don't have them, which is weird
u sure bot has the perm? can u show the exact exception paste the traceback here
sure hold on
The bot has the same perms I have.
Traceback (most recent call last):
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1021, in invoke
await self.prepare(ctx)
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 925, in prepare
if not await self.can_run(ctx):
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\hybrid.py", line 526, in can_run
return await super().can_run(ctx)
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1288, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\utils.py", line 703, in async_all
for elem in gen:
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 1288, in <genexpr>
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "E:\Python Projects\UniBot Rework\.venv\lib\site-packages\discord\ext\commands\core.py", line 2210, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Deafen Members permission(s) to run this command.```
Clearly have the permission too
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
same issue
i gave it all permissions to the channel with my role.
Im pretty sure its broken.. what goes off guild permissions? instead of channel permissions?
!d discord.ext.commands.has_guild_permissions try this check
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).
New in version 1.3.
depends if it's a multi server bot i would say yeah it's easier to manage single server perhaps channel is more atomic
Multi server bot
again then its probably a channel perms issue
It has to be a bug, i gave that channel n category all permissions, all roles including everyone. I think commands.has_permissions is bugged with those 3...
dont forget to save after adding role and user with relevant perms
Yes ik lol
doubtful such a bug would've been caught long ago
ill send a video π
How often can we call change_presence?
@shrewd apex (sorry for ping)
Category, channel, role all has the perm.
Unless you see an issue in it that I truly do not see.. then I think its a bug.
All 3 of these give the same error using commands.has_permissions, but when i use commands.has_guild_permissions it works. I think has_permissions is truly bugged with these 3..
is that a hybrid command?
yes
add ur developer role to the channel. did u add that?
also if ur using guild_only decorator u might as well leave it with have_guild_perms u can raise this issue in the dpy server
do they have a mod mail?
It appears my message got hidden away in all the mass messages ;-; #discord-bots message
Anybody know? ;-;
just create a help post
give a gap of 2-5 min ig?
U sure? I was thinking it'd be a few times a minute
Would a 20 second cooldown/gap between changes suffice?
seems a bit too frequent imo but u can try should be fine i suppose
I did
I mean, you did see I checked everything... do you see a possible error on my end?
Well i see now, it wasn't a channel perm. I feel stupid now. But that is reasonable, I was thinking it would give a differen't error if it wasn't a correct perm for channels. But that is fine.
what was the issue
So channels don't have those 3 perms lol
only guild does
so it was kinda obvious it was gonna give that error. I am just dumb and didn't read the channel perms.
Trying to make a basic bot.. why the heck isnt this command working? ;-;
from discord import Intents, ActivityType, Activity, Embed
from discord.ext.commands import Bot, command
from discord.ext import commands
from discord.ext import tasks
import asyncio
import requests
import json
# Read server information from servers.json
with open('servers.json', 'r') as file:
config = json.load(file)
class MyBot(Bot):
def __init__(self, config):
self.config = config
self.server_population = []
super().__init__(
command_prefix=f"!",
intents=Intents.all()
)
@command(name='pop')
async def server_pop(self, ctx):
print("POP!")
embed = Embed(title="Server population information!")
for pop_info in self.server_population:
embed.add_field(name=f"{pop_info['server_name']}", value=f"{pop_info['online']}/{pop_info['max']}", inline=False)
embed.set_footer(text="Footer information")
await ctx.send(embed=embed)
commands.command decorator is for use with Cogs.
exactly, so commands.command decorator won't work
What decorator do I need?
there is none for subclasses of Bot. you usually create an instance of your Bot, and then use the bot.command decorator on regular functions
I've tried @Bot.command() but I get an error
I guess I need to modify this bot to have cogs I guess lol
class MyBot(Bot):
...
bot = MyBot()
@bot.command('pop')
async def server_pop(ctx):
...
Ya wont work for my setup. Ty tho. I'll just make a proper bot with cogs and what not
it started with 4 files, about 75 lines total.
;-;
now many folders and files later.
I am thinking of creating my discord bot with drawing AI, what good drawing free AI with it's API would you recommend to use?
yo guys wanna ask for opinion about slots minigame on my discord bot what is an ideal weight/multiply ratio so the game feels satisfying to play but not too rewarding
symbols = [':cherries:', ':lemon:', ':tangerine:', ':watermelon:', ':bell:', ':gem:', ':star:']
weight = (45, 35, 25, 20, 15, 7, 5)
multiply = (6, 9, 12, 15, 30, 50, 150)
spin = random.choices(symbols, weights=weight, k=3)
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.reactions = True
intents.messages = True
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='!',
intents=intents,
status=discord.Status.online,
case_insensitive=True,
help_command=None,
owner_ids=[1096379840011190272],
activity=discord.Activity(
type=discord.ActivityType.watching,
name="Anime Hub"))
self.initial_extensions = ["cogs.general"]
async def setup_hook(self):
for extension in self.initial_extensions:
try:
await self.load_extension(extension)
print(f"{extension} cog has been loaded.")
except Exception as e:
print(f"Failed to load extension {extension}. Error: {e}")
async def on_ready(self):
print(f'We have logged in as {self.user.name}')
print(self.cogs, self.extensions)
bot = MyBot()
bot.command()
async def greet(self, ctx):
if ctx.message.content.startswith('$greet'):
channel = ctx.channel
await channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await self.wait_for('message', check=check)
await channel.send(f'Hello {msg.author}!')
@bot.command(name='list_cogs', hidden=True)
async def list_cogs(ctx):
"""List all loaded cogs."""
loaded_cogs = [cog for cog in bot.cogs]
await ctx.send(f'Loaded cogs: {", ".join(loaded_cogs)}')
bot.run("TOKEN_HERE")
MAY IK whats going wrong here??
hey, i was wondering if someone could tell me all the ways a bot can ask for input, like you got slash commands, buttons but is there also something like a prompt?
that was a mistake while copying but that's not the case my bad
Modals
thank you, that is why i did not find it most likely
@sick birch can u help?
What problem do you facing ?
cmds not working
excuse me sir how to i handle to many reqeuts database nextcord
import nextcord
from nextcord.ext import commands
import asyncpg
bot = commands.Bot(command_prefix="!", intents=nextcord.Intents.all())
async def create_db_pool():
bot.pg_con = await asyncpg.create_pool(
"..."
)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command()
async def hello(ctx):
await ctx.send("Hello, I am a robot")
bot.loop.run_until_complete(create_db_pool())
bot.run("...")```
this error
```bash
asyncpg.exceptions.TooManyConnectionsError: too many connections for role ...```
Is it showing any error on console?
its not
greet cmd not working right?
greet test help
none of them working
i have made a test cmd in cog even it doesnt work
none of the cmds work
!message_content
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
!list_cogs doesnt work
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
Is it possible to send multiple embeds in the same message?
!d discord.Messagable.send - you can set the embeds argument to a list of embeds
No documentation found for the requested symbol.
I died
What doesn't work now?
!list_cogs
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
!pypi nacl
!pypi pynacl
so i have a code i which i want the text of the message to be changed once a user clicks on the button, but i think i am doing something stupid:
start_time = time.time()
class PingView(discord.ui.View):
def __init__(self):
super().__init__()
button = discord.ui.Button(label="Click Me", disabled=False)
button.callback = self.on_button_click
self.add_item(button)
async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction = None):
if interaction is not None:
# Change the label to "Stop it" when the button is clicked
button.label = "Stop it"
button.disabled = True
await interaction.response.edit_message(content="Button clicked! Label changed to 'Stop it'.", view=self)
@commands.guild_only()
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
try:
latency = bot.latency * 1000
uptime_seconds = int(time.time() - start_time)
uptime_days = uptime_seconds // (24 * 3600)
uptime_seconds %= 24 * 3600
uptime_hours = uptime_seconds // 3600
uptime_seconds %= 3600
uptime_minutes = uptime_seconds // 60
uptime_seconds %= 60
uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"
# Create an instance of PingView and pass it as the view parameter
await ctx.send(f"### Pong! π \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=PingView())
except Exception as e:
await ctx.send(f"An error occurred: {str(e)}")```
there r no errors but the text wont update
interaction is first argument given
button is second
and you should not provide a default value for any of those
i fixed that before seeing your message, got a new error, i am stupid
probably did something more stupid now:
2024-02-06 20:59:18 ERROR discord.ui.view Ignoring exception in view <PingView timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Click Me' emoji=None row=None>
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 247, in click_button
button.label = "Stop it"
^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'label'```
class PingView(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Click Me", style=discord.ButtonStyle.secondary)
async def click_button(self, button: discord.ui.Button, interaction: discord.Interaction):
# Change the label to "Stop it" when the button is clicked
button.label = "Stop it"
button.disabled = True
await interaction.message.edit(content="Button clicked! Label changed to 'Stop it'.", view=self)
@commands.guild_only()
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
try:
latency = bot.latency * 1000
uptime_seconds = int(time.time() - start_time)
uptime_days = uptime_seconds // (24 * 3600)
uptime_seconds %= 24 * 3600
uptime_hours = uptime_seconds // 3600
uptime_seconds %= 3600
uptime_minutes = uptime_seconds // 60
uptime_seconds %= 60
uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"
# Create an instance of PingView and pass it as the view parameter
view = PingView()
await ctx.send(f"### Pong! π \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)
except Exception as e:
await ctx.send(f"An error occurred: {str(e)}")```
nope you still didnt fix that
and this error is cause of that
okay okay lemme see my code again, i think i misunderstood it
not sure what to do now tbh bash An error occurred: MessageReference.init() takes 1 positional argument but 3 were given
start_time = time.time()
class PingView(discord.ui.View):
def __init__(self):
super().__init__()
self.click_count = 0
async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
self.click_count += 1
if self.click_count == 1:
button.label = "Stop it!"
elif self.click_count == 2:
button.label = "Stop it!!"
await interaction.message.edit(content="I am warning you", view=self)
elif self.click_count == 3:
url = "https://www.example.com" # link button
await interaction.message.edit(content="Link Button", view=LinkView(url))
self.stop() # ending button
@commands.guild_only()
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
try:
latency = bot.latency * 1000
uptime_seconds = int(time.time() - start_time)
uptime_days = uptime_seconds // (24 * 3600)
uptime_seconds %= 24 * 3600
uptime_hours = uptime_seconds // 3600
uptime_seconds %= 3600
uptime_minutes = uptime_seconds // 60
uptime_seconds %= 60
uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"
# Create an instance of PingView and pass it as the view parameter
view = PingView()
message = await ctx.send(f"### Pong! π \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)
# Set the message reference for the view to perform edits
view.message_reference = discord.MessageReference(message.id, message.channel.id)
except Exception as e:
await ctx.send(f"An error occurred: {str(e)}")```
MessageReference takes kwargs
oh yeah; im dum
how do i make a command cooldown in cogs
error:
An error occurred: MessageReference.init() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```
code:
class PingView(discord.ui.View):
def __init__(self):
super().__init__()
self.click_count = 0
async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
self.click_count += 1
if self.click_count == 1:
button.label = "Stop it!"
elif self.click_count == 2:
button.label = "Stop it!!"
await interaction.message.edit(content="I am warning you", view=self)
elif self.click_count == 3:
url = "https://www.example.com" # rick astle
await interaction.message.edit(content="Link Button", view=LinkView(url))
self.stop() # end buttons
@commands.guild_only()
@bot.hybrid_command(name="ping", description="Provides bot latency.")
async def ping(ctx):
try:
latency = bot.latency * 1000
uptime_seconds = int(time.time() - start_time)
uptime_days = uptime_seconds // (24 * 3600)
uptime_seconds %= 24 * 3600
uptime_hours = uptime_seconds // 3600
uptime_seconds %= 3600
uptime_minutes = uptime_seconds // 60
uptime_seconds %= 60
uptime_str = f"{uptime_days}d {uptime_hours}h {uptime_minutes}m {uptime_seconds}s"
# Create an instance of PingView and pass it as the view parameter
view = PingView()
message = await ctx.send(f"### Pong! π \n> **Latency:** {latency:.2f} ms \n> **Uptime:** {uptime_str} \n", view=view)
# Set the message reference for the view to perform edits
view.message_reference = discord.MessageReference(message.id, fail_if_not_exists=False)
except Exception as e:
await ctx.send(f"An error occurred: {str(e)}")```
Traceback (most recent call last):
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Naseer\Desktop\That one server\cogs\Fighting_Commands.py", line 305, in fight
self.bot.cd[user]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")
~~~~~~~~~~~^^^^^^
KeyError: 502684803783720982
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 502684803783720982
user = ctx.author.id```
I dont understand.?
and in my on_message it says
if user not in bot.cd:
bot.cd[user] = {"F":"β", "M":"β", "C":"β"}
but this is a command
@tiny coyote Is user defined beforehand in the dict?
This isn't an object you make yourself, you can use this.
!d discord.MessageReference.from_message
classmethod from_message(message, *, fail_if_not_exists=True)```
Creates a [`MessageReference`](https://discordpy.readthedocs.io/en/latest/api.html#discord.MessageReference) from an existing [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).
New in version 1.6.
What was the issue?
I thought the dict was created after feeding it values but i was wrong
Im not sure really
how do i put a flask into my discord bot
So I can use it for uptime robot for uptime logging
Well the keyerror comes from a key, in this case the user, wasn't in the dict.
bot.cd = {}
if message.author.id not in bot.cd:
bot.cd[message.author.id] = {"F":"β", "M":"β", "C":"β"}
print(f"{user} is the given attribute")
i changed user and put message.author, no more errors thankfully BUT it doesnt do what its suppose to do
self.bot.cd[user]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")```
!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) 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).
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#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), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#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) is a new alternative leveraging structural concurrency; it allows for waiting for a group of related tasks with strong safety guarantees.
no error, i created another command that shows you what the variable holds but it says β
So I run my flask with that?
Well if you want both processes to be online, but personally I'd use whatever website you're using and just use their API.
im not sure if this is the issue but i used asyncio.sleep to change the variable back to what it was after the cooldown timer..@cloud dawn
self.bot.cd[ctx.author.id]["F"] = discord.utils.format_dt(now + timedelta(minutes=2), style = "R")
await asyncio.sleep(120)
self.bot.cd[user]["F"] = "β"
Ok
May I ask what this is for?
thats to show how much time the user has after command has been use
So a cooldown function.. or..?
