#discord-bots
1 messages · Page 372 of 1
You should not use just a json file
Unless you're keen on poor performance and having your data randomly corrupted
just use a file based database if u dont wanna put that much effort
sqlite is super fast to spin up and use if you know sql basics
SQLite scales incredibly well, it's less about scale and more about whether or not you need a server client model
Like that's a good thing lol
it's pretty much unnecessary for file based dbs no?
ah
Not sure what you mean by "file based", or what you think is going on under the hood with things like Postgres
(Files)
.db files
Anywho probably a better convo for #databases
!paste
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.
https://paste.pythondiscord.com/QQFQ
why this bot dont wanna send deal amount after incorrect

where exactly is the error
and what's the error or where does the code stop running
when the user clicks incorrect, the bot deletes the messages but does not resend the deal amount request
There isn't
it doesnt send the embed and the view?
yes

right thank you love you, havent done this in a long time
hey you know what i managed to go around it, turns you can invoke process_commands, so i simply added that to all the if scenarios and it works! still thanks tho
I would recommend using a listener instead for simplicity
You should only need to override and run process_commands if there are cases where you don't want to process commands
yo guys i have a small question
how can i get the message from discord api
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
async def kick(self, ctx, message: discord.message):
for some reason it doesnt allow me to use the message content
why does it give me it here tho
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
async def on_message(self, message):
so that event has the message already included?
ur talking about a command ur defining
Discord sends it to the bot as a part of the event payload
oh ok
whats the / parameter?
marks id as a positional parameter
what does that mean
Google is your friend here
In [1]: def foo(a, b, /):
...: return a, b
...:
In [2]: foo(1, 2)
Out[2]: (1, 2)
In [3]: foo(1, b=2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 foo(1, b=2)
TypeError: foo() got some positional-only arguments passed as keyword arguments: 'b'
just means u cant pass the stuff as keyword arguments they are strictly positional
there is also * which is responsible for keyword arguments
well yeah u need to pass it in order in such a case
nvm found it
If you want someone to pass a message in for a command, consider making a message context menu instead
following up on this, could there be any work around? like maybe overriding the interaction_check method of CommandTree Or smth?
what is that?
You're probably thinking about this the wrong way, it really depends on what you're trying to accomplish but in general it's not good to mutate standard objects dictated by discord
im basically trying to replicate a kick command but to do that i need to find the content in the message so i can know which user to kick
Why not use the built in kick command?
well im trying to learn here
You can learn without reducing security
how am i reducing security?
my only goal is to have a method which forms and sends the embed to the context location. While using prefix commands I just made a customcontext class which had a send_embed method. that way I did not have to
await ctx.send(embed=embed) (and also form the embed)
and just had to
await ctx.send_embed(text)
There's a million other things you can make besides replicating something that already exists but worse that is also bad for security
im not ever willing to publish the bot in the market..
im just developing discord bots to learn python
Knowing the tools you have available is a part of learning
well i'd like to know how they work
But why a kick command? You could replicate the 8000 other operations on the api that also aren't sensitive or security gated. There's a reason why people pick that specifically, and it's due to misinformation
what can i replicate?
Look at anything you do in discord
Almost every button or menu has an api endpoint backing it
From a learning perspective, kicking or banning a member is no more interesting or complex than changing their nickname or moving them between voice channels or muting them etc etc. All single api calls, it's just the former are sensitive and have very specific protections on them that you aren't going to replicate
make some ai response command based on message context, or make some code evaluation based on a message context menu so may ways lol get creative
ok
You may want to read the new developer policy before recommending the former
hmm it has prohibitions on like gen ai? lemme take a look
Says "do not use message content to train AI models without discord's consent", paraphrased
but is training same as prompt generation?
like i actively want to generate some response out of my query as an user does that violate the tos?
Not a lawyer, but I personally wouldn't fuck with passing any user content into anything vaguely AI
Nor do I ever want someone doing that with my content in any capacity
hmm fair i suppose
And if you didn't design and host the model yourself, you have no idea what it's doing when you pass a string into it
Going out on a limb and guessing that a vast majority of bot developers are not also professional AI scientists brewing their own models
im pretty sure mee6 and other bots use ai
mee6 also literally scams people
scams?
Not a good measuring stick to decide what's morally okay to do with your work lol
isnt that shit the most popular bot
That is not mutually exclusive with being shitty, unfortunately
The new policy is also not in effect yet
It was just announced like yesterday
oh
watch TTS' video about it
i remember when they were slowly making each feature 'premium'
Yeah, i'm not paying $90 to send custom embeds
should i make language switch for my bot?
Unlikely it's worth it unless you have a personal preference
Most of the major libraries have feature parity
Hey, why is my bot not able to sync the application commands to my server
await self.load_extension("Luna.extensions.general")
if self.settings.AUTO_SYNC_APP_COMMANDS:
synced_commands = await self.tree.sync(guild=discord.Object(self.settings.GUILD_ID))
print(synced_commands)
# Output: []
.I have a GroupCog in the general.py file. Also, when I log the information on startup, discord.py does recognize the general group though it does not sync.
I haven't use dpy in like 2 years 💀
You shouldn't ever be auto syncing
But check to see if your commands are also registered to the same guild
Well, I turn it off after it gets synced so yeah
why not just have a command for syncing
Can we solve the main issue here pls? 🗿
^
If your commands are "global", and you're syncing to one guild. Only commands that have also been set to sync to that guild are synced.
Oh shit I forgot to copy it to global 💀 alrght thanks
👍
This does matter as you will quickly rate limit yourself and be unable to do anything for days
is the rate limit that long?
hmm
iirc gamecracks posted about the amount of times u can sync commands which is counted towards rate limits i think that happens when creating and deleting commands afaik
wait so auto syncing is the reason i get rate limited?
i do run my bot multiple times
if you're syncing on start up, and then restarting your bot every time you make a change, that will get you ratelimited in the blink of an eye
ye i do that
well i “assumed” that its the only thing that can get me rate limited
You can get rate limited on literally any action you do that talks to the api
hey guys
so i need help
2024-06-08 20:40:28 ERROR discord.ui.view Ignoring exception in view <SupportView timeout=None children=1> for item <SupportDropdown placeholder='Select a support option' min_values=1 max_values=1 disabled=False options=[<SelectOption label='General Support' value='general' description=None emoji=None default=False>, <SelectOption label='High Rank Support' value='high_rank' description=None emoji=None default=False>, <SelectOption label='Management Support' value='management' description=None emoji=None default=False>]>
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/bot.py", line 44, in callback
await self.create_support_channel(interaction, channel_name)
File "/home/container/bot.py", line 55, in create_support_channel
channel = await interaction.guild.create_text_channel(channel_name, category=self.category, overwrites=overwrites)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/guild.py", line 1369, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/guild.py", line 1227, in _create_channel
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
One of the things in the overwrites dict was None
yea i still dont work
If it's the same error, you didn't fix it. If it's a different error, we'll need that.
You also should strongly consider generating threads rather than channels for this purpose.
i fixed it lol
i just retyped it all and it worked
Best way to grow your discord bot or make it be seen?
My discord bot is integrated with a private Plex Server, users can look up movie titles and if it's on the server the bot will respond with an embed with information about the movie. Is there ways to get neater formatting out of this, like reduce some of the empty space?
i guess if you want a smaller one just use embed description, and format them as
Title: The Room
Year: 2003
...
using embed fields only get you that much space
alternatively just change around how you're setting up ur embed if you want it to be smaller
i forgot director but it gets the point across
but because this is a specific use case and probably only you and a few others will utilize it you can assume people know what each thing is, i.e the title and link not needing its own field and just paring it in the embeds actual title and url
that makes sense, I appreciate the suggestions
The story has some sauce to it ngl 🗿
Anyone here knows how to create telegram bot with python? I just want the bot to send a message when start button is pressed
You can ask in #1035199133436354600 , in this channel all people will only answer questions regarding discord bots
How can I handle this rate limit? [WARNING ] discord.http: We are being rate limited. What event shoud I use?
@bot.event
async on_error()```
is not called and
@bot.event
async def on_request_error(response, data):
is not called.
There is no documentation for other error handling events that I can find in discord.py docs. I mean it is hard to find something there in general.
That's logged while doing requests
Nothing it called for it
You should check the routes it's called for and "fix" your code spamming that
is there a package for instagram so whenever a specific person posts a reel it sends it in a channel through a webhook?
I made my bot to do a lot of stuff so it can get rate limited for tests.
Aha
Use web scraping.
And I want when it gets timeouted to send message or to do some action.
I just realize that it can't do any action, because it is rate limited.
But still. How can I do it?
I personally don't think there is a way for users to "handle" it..
I'm not sure if this is allowed but I would suggest opening a post in the discord.py server at https://discord.com/channels/336642139381301249/985299059441025044 since there are more people that know about this stuff
import discord
from discord.ext import commands
def setup(bot):
bot.help_command = HelpCommand()
class HelpCommand(commands.HelpCommand):
def __init__(self):
super().__init__(command_attrs={
'help': 'Shows help about the bot, a command, or a category'
})
def command_not_found(self, string):
return
async def send_bot_help(self, mapping):
embed = discord.Embed(color=0xfd7aff,
title=self.context.bot.user.name,
description=f"Use `{self.context.prefix}help cog_name` to see the commands")
cogs = []
for extension in self.context.bot.cogs.values():
cogs.append(f"- {extension.qualified_name}")
embed.add_field(name="Cogs", value="\n".join(cogs))
await self.context.send(embed=embed)
async def send_cog_help(self, cog):
embed = discord.Embed(color=0xfd7aff, title=cog.qualified_name.title())
commands = []
for cmd in cog.get_commands():
commands.append(cmd.name)
embed.description = f"`{'`, `'.join(commands)}`"
await self.context.send(embed=embed)
async def send_command_help(self, command):
embed = discord.Embed(color=0xfd7aff,
title=command.name,
description=command.help if command.help else "No help for this command found...")
await self.context.send(embed=embed)
async def send_group_help(self, group):
embed = discord.Embed(color=0xfd7aff,
title=group.name,
description=group.help if group.help else "No help for this command found...")
subcmds = []
for gc in group.commands:
subcmds.append(f"- {gc.name}")
embed.add_field(name="Subcommands:", value="\n".join(subcmds))
await self.context.send(embed=embed)
``` in a cog for a help command. taken from an old discord bot of mine
idk what line the error is coming from
setup func must be async in discord.py 2.0+
You should print/log the full trackback tho
Hm?
It has nothing to do with the help conmand
yeah, i just mistyped something, thats all
error:
def setup(bot):
bot.help_command = HelpCommand()
Correct:
async def setup(bot):
await bot.add_cog(HelpCommand(bot))
Lol no
You don't add a HelpCommand as a cog
You aren't required to call add_cog in the setup func fwiw lol
it just prints err to a message
That's bad

Or ```py
import logging
logging.error("message", exc_info=error_or_bool)
how can i get avatar url of a interaction.user
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
👍
I would recommend .display_avatar
That's the setup part which looks pretty good yes
logging.info/debug/error can be used to actually use it yourself
is it possible to open a modal with a slash command
yes
.... help
Show full code
if i can get the user's status as user.activities[0].name, how can i get the user's bio?
enable this
ah
thank u
How did toggling the intent in the developer portal solve an attribute error LMFAO, completely unrelated
Either the issue is still not fixed or it wasn't that the error
it doesn't work :v
that was the only thing that came to mind lmao but Krypton can help you

uh nuh
can you show whole code please?
no
just enable the required intents, not everything
Code:
view = PaginatorView(embeds, self.bot, ctx.author)
print(view.children)
view.message = await ctx.send(embed=view.initial, view=view)
print(view.message.components)
Console:
[]```
why?
why what
why is the view.message.components = []
shouldn't it be the buttons?
looks like you didnt attach those buttons to a view
class View(ui.View):
def __init__(self, ...):
# Missing self.add_item()
atleast I think thats the case
if i can get the user's status as user.activities[0].name, how can i get the user's bio?
.
bro you can see the children of the view
on printing view.children - the first print
the list lol
You cannot. Discord's bot API doesn't give those out
gotchu
hi who can help me
Feel free to ask your question and people who know the answer will
guild.channels includes categories too, any way to get only channels?
could do [channel for channel in guild.channels if not isinstance(channel, discord.CategoryChannel)]
yee
Is it possible to make a discord bot run a command on another bot?
I wanna try making an auto bump bot
no
Bots cannot perform interactions. If it's a text command, sure why not if the bot allows it and doesn't mind you doing it
so i ws using selenium for screenshotting a webpage but my bot gets ratelimited, could i know how many requests i can make or how many times can i screenshot a webpage?
the bot itself is ratelimited or?
bot itself
screenshotting another website shouldn't affect those ratelimits, what else are you doing?
def take_screenshot(url):
driver = webdriver.Chrome()
driver.get(url)
screenshot_path = "screenshot.png"
driver.save_screenshot(screenshot_path)
driver.quit()
return screenshot_path
@bot.command()
async def screenshot(ctx, *, url: str):
screenshot_path = take_screenshot(url)
with open(screenshot_path, "rb") as file:
screenshot_file = discord.File(file)
await ctx.send(file=screenshot_file)
can you show the ratelimit message/warning
wai
you do get a message saying you're being ratelimited do you?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
other error is of selenium i think
you're not being ratelimited its because selenium is blocking (probably especially so when taking screenshots n stuff)
https://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
so is there something i could do to fix it?
you'll want to run your synchronous function in an executor, something like await loop.run_in_executor(None, sync_func, *args)
asyncio.to_thread
i thought to_thread was worse
it's a wrapper around run_in_executor
oh TiL
Lib/asyncio/threads.py lines 12 to 25
async def to_thread(func, /, *args, **kwargs):
"""Asynchronously run function *func* in a separate thread.
Any *args and **kwargs supplied for this function are directly passed
to *func*. Also, the current :class:`contextvars.Context` is propagated,
allowing context variables from the main thread to be accessed in the
separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
"""
loop = events.get_running_loop()
ctx = contextvars.copy_context()
func_call = functools.partial(ctx.run, func, *args, **kwargs)
return await loop.run_in_executor(None, func_call)```
guys, did discord bots break for you guys? Im on discord.py 2.0.1
2024-06-09 15:20:42 INFO discord.client logging in using static token
2024-06-09 15:20:43 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: c510624444dec1c4ff79cd7bf62b9999).
Traceback (most recent call last):
File "/home/abcdefgh/test123-v3/main.py", line 519, in <module>
bot.run(os.getenv('tok'))
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
[.... removed stuff from here]
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/guild.py", line 487, in _from_data
self.stickers: Tuple[GuildSticker, ...] = tuple(
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/guild.py", line 488, in <lambda>
map(lambda d: state.store_sticker(self, d), guild.get('stickers', []))
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/state.py", line 379, in store_sticker
self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 273, in __init__
self._from_data(data)
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 416, in _from_data
super()._from_data(data)
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 280, in _from_data
self.url: str = f'{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}'
File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/enums.py", line 534, in file_extension
return lookup[self]
KeyError: <StickerFormatType.unknown_4: 4>
The bot was up for a year and it went down today
this was fixed in dpy v2.2.3
im not completely sure there may be a couple things but not many (take that with a grain of salt idk the amount of breaking changes since 2.0.1)
I see I see..
updating will fix that problem though
no problem
Can i get some bot help, webook2 = Webhook.from_url(data["webhook", client = bot])
^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
thats the error code
webook2 = Webhook.from_url(data["webhook", client = bot])
Thasts the code
Check where your ] is
for those of you that use sqlite databases with your bot, how prone are the databases to becoming corrupted?
well the thing is i had to change it as im trying to send a view using webhook2
and apparently its writen like that but its erroring
That doesn't really address the fact that you're trying to subscript on whatever data is with ["webhook", ...]
so how should i fix it?
Subscript on it with a valid key
ah okay
do you think you coudl help with the sending a view part?
import discord
from discord import ui
class ButtonSendCode(ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Send Code", style=discord.ButtonStyle.green, custom_id="persistent:button_one")
async def button_one(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("hi")
``` - Filename is button_sendcode.py its then refereneced as ButtonSendCode
await webhook.send(view= ButtonSendCode()) and i tried this but it just errors
and what is the error?
It just doesnt send it
like it doesnt send/show the button
@fast osprey
changed the code to this webhook2 = discord.Webhook.from_url(data["webhook"], session=session)
await webhook2.send("",view= ButtonSendCode())
however get the issue ```ValueError: Webhook views require an associated state with the webhook
To send components with a webhook it needs to be a webhook owned by the application (your bot)
Which can be done by, e.g.
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
And you can also fetch a webhook based on its ID
!d discord.ext.commands.Bot.fetch_webhook
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) with the specified ID.
Changed in version 2.0: `webhook_id` parameter is now positional-only.
can anyone help me with this
@bot.event
I tried that as well
and what does it say?
no parenthesis
oh I am dumb I was basing it off of commands thx
nw
someone know a way to profile a bot memory usage?
wtf.. i got banned on gg/dpy xD
hey everyone, ive been struggling with this for a while and would love some help if possible!
basically, when someone sends a gif, i would like it to show the gif inside of the embed (you can see in the image attached it just shows the gif link, not the actual gif)
any help is greatly appreciated
!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.
i think this should work
alright, ill go try that out
i can see where the gif would be, but it seems to just load forever
i was looking around and found this: #1243898327435579412
what i think i would need to do then is get the direct image url, but in order for it to work with whatever gifs are sent, the bot would have to get that somehow? so im not too sure how i would do that
Hi, trying to make a proper help command
Shown in the image, on the bottom of the help command there are two arguments and next to those arguments it says that there's no description given, but how do I give a description
I've been searching the docs and I'm confused on that
!d discord.ext.commands.parameter
discord.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)```
A way to assign custom metadata for a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)'s parameter.
New in version 2.0.
Examples
A custom default can be used to have late binding behaviour.
```py
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
await ctx.send(f'Hello {to.mention} :wave:')
nvm
can somebody help me?
My code is: ```py
class ConfirmView(discord.ui.View):
def init(self, url, filename, title, artist, ctx):
super().init(timeout=None)
self.url = url
self.filename = filename
self.title = title
self.artist = artist
self.ctx = ctx
@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
url, title, artist, thumbnail = get_youtube_video_info(self.url)
embed = discord.Embed(description=f"**Το `{title}` αρχίζει να κατεβένει, μόλις κατέβει θα σταλθεί εδώ.**", color=discord.Color.dark_red())
embed.set_author(name=button.user.name, icon_url=button.user.avatar)
message69 = await button.response.send_message(embed=embed, ephemeral=True)
filename, title, artist, thumbnail = download_youtube_video(self.url)
await message69.edit(file=discord.File(filename), ephemeral=True)
os.remove(self.filename)
self.stop()```
and the error is: await message69.edit(file=discord.File(filename), ephemeral=True) AttributeError: 'NoneType' object has no attribute 'edit'
why?
.send_message doesn't actually return the Message
you have to use await interaction.edit_original_response(...)
and await interaction.send_original_response too?
no, you can leave the .send_message as it is
how can I send a file on the await interaction.edit_original_response()?
it takes attachments kwarg which accepts a list of discord.File
Yeah I fixed it
So it isn't sending the message to the user?
No it just errors in the console about the error itself (missing any role)
uh?? So it's not sending the error to the user right?
No, you can try it to see what I mean
Need an error handler for your app (slash) commands? These are handled on the CommandTree. You can set one using the decorator or subclass it (recommended).
Documentation
- CommandTree.on_error
- CommandTree.error (decorator)
How
- Subclassing
CommandTree:?tag treeerrorsubclass - Using the decorator:
from discord import app_commands, Interaction
bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a CommandTree you define.
tree = bot.tree
# can't find your tree? -> ?tag definetree
# this will function as a global error handler for app commands
@tree.error
async def on_app_command_error(
interaction: Interaction,
error: app_commands.AppCommandError
):
...
- In a Cog/Extension:
?tag treeerrorcog - Per command:
?tag app_command_error


That is only for discord.py, it will not help those who use a fork

only discord.py calls it "app commands" and they literally said "in the dpy docs"
Yeah, on_app_command_error has no results in the docs
whered you find this?
it's a tag in the discord.py server
but my on_error thing is in a class, decorators dont work in classes do they?
im confused sorry
do you want it a cog?
no this is the main code, no cogs
anyone know anything about this? https://www.cooldown.ai?utm_source=discord&utm_medium=server&utm_campaign=outreach
Cooldown.AI is the first all-in-one, AI-powered platform to automate growth, tedious tasks, and help you engage and earn more from your community.
If you want an event inside a class you must use the commands.Cog.listener() decorator
@barren shoal
fixed it
on_error for CommandTree is awkward in that you can't use regular listeners for it, you'd have to override it directly to apply a global error handler
https://github.com/thegamecracks/theticketbot/blob/main/src/theticketbot/cogs/errors.py#L276-L285
src/theticketbot/cogs/errors.py lines 276 to 285
def setup_events(self):
self._old_command_error = self.bot.on_command_error
self.bot.on_command_error = self.prefix_handler.handle # type: ignore
self._old_tree_error = self.bot.tree.on_error
self.bot.tree.error(self.tree_handler.handle)
def teardown_events(self):
self.bot.on_command_error = self._old_command_error
self.bot.tree.error(self._old_tree_error) # type: ignore```
I want to create a discord bot for pokedex the stats data i wanna use is in a typescript format how can i use it
I didn't know why I don't use discord.py and look in the documentation why I use a fork 😅
ensure the get_youtube_video_info function is async if you're awaiting it
How do I do something so that my bot commands can only be used on servers?
use the on_command event and make a check and see if the channel is not private
just search for it on the docs
😭
Slash commands or?
prefix
@commands.guild_only() check
And for DM-only commands?
Do you mean that users can use the commands in any DM?
In order for users to be able to use commands in DM, they must be slash commands and they must be linked to the new discord feature that allows users to install them. I'm not sure if discord.py already has this built in. It is still in Beta
and commands so that they can be used in dm and servers?
as I mentioned before, if you want the commands to be usable in any DM you must use the new discord feature. About the commands that can only be used on servers use the decorator you were shown before
@commands.dm_only()
but doesn't that apply only to the Dm of the bot?
🤔
do you know if discord.py already has this function that allows users to use commands in any DM?
Yeah in the master branch which you install from github
!d discord.app_commands.allowed_installs
@discord.app_commands.allowed_installs(guilds=..., users=...)```
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
!d discord.app_commands.allowed_contexts
@discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)```
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
nice! thx
hey, i need help
theres no errors in the console but it only says Please select a support option.
@pale zenith sir, even if I put @commands.guild_only()
the command is still responding and working in dm
show your code, please
I see, and did you restart the bot and save the file?
thx now work
can yall help me
don't ask to ask
they didn't willi scroll up
please forgive me leo
the code is kinda bad and I don't have the mental capacity to think at the moment
so I'd rather not take the commitment of helping them 😔
it's okay
@bot.event
async def on_message(message):
if isinstance(message.channel, (discord.TextChannel, discord.VoiceChannel)):
if isinstance(message.channel, discord.TextChannel) and message.content.startswith(bot.command_prefix):
await message.send('hi')
await bot.process_commands(message)``` looks good?
You shouldn't handle commands this way
instance look good?
Just put those checks inside your commands
"good" is saying too much but those sure are some valid valid isinstance calls
Can anyone tell me what it's for:
message = await interaction.original_response()```
Fetches the original interaction response message associated with the interaction.
how can i fix this error?
i have no error in code, ids are correct for channels,roles etc..
Anyone know why the commands are not syncing?
Bot runs fine, just doesn't show the commands in discord servers.
discord.py
intents = discord.Intents.all()
intents.message_content = True
Bot = commands.Bot(command_prefix="/", intents=intents, case_insensitive=False)
@Bot.event
async def on_ready():
await Bot.tree.sync()
print(f'We have logged in as {Bot.user}')
@Bot.tree.command(
name= "setup",
description="Setup your Cooper Bot!"
)
async def setup(interaction):
await interaction.response.send_message("Testing!")
with open(os.getcwd() + "\Database\BotInfo\info.json") as json_file:
json_decoded = json.load(json_file)
Bot.run(json_decoded["Token"])
The print line in on_ready does run
Could I also just make a list of every discord that a client is in and loop through syncing each, one by one? If so, how would I sync each discord command, as they require a guild argument in @client.command()
Bot runs fine, just doesn't show the commands in discord servers.
your code snippet seems fine, chances are that your desktop app needs to be reloaded (ctrl+R) to see the new command
Could I also just make a list of every discord that a client is in and loop through syncing each, one by one?
syncing is ratelimited quite heavily so i'd advise against syncing every guild at once; omittingguild=simply gives you a global command, like you've already defined
defer the interaction
It may be taking more than 3s
but, it doesn't says "the interaction didn't respond" so, it may not fix the issue
it fetches the original interaction response message associated with the interaction
any clues on how that could happen?
i had this same problem with slash commands
It may be the intents
all 3 r on
You didn't get any errora in the code you said?
yeahh, maybe code logic?
wait no i tried the same bot with no code
cant be that.. not sure.
alright so i tested it haha, same code.. switched to the discord bot (all same settings) and it didnt work. went to another one and it did
very odd.
does anyone know how to get a discord webhook name using python im able to get id but i want a name like print('Logged in as {webhook_name}')
indeed xd
!d discord.Webhook.from_url
classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
pass the url parameter as your webhook url
this will return a Webhook object
!d discord.Webhook
class discord.Webhook```
Represents an asynchronous Discord webhook.
Webhooks are a form to send messages to channels in Discord without a bot user or authentication.
There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.
The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.
For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
guys my brain just shut down after not using python for months, can someone tell me how to fix this
install discord.py
i already did, im not sure why its not working
make sure you're on the same environment and you installed it in it
ctx.guild.bans returns a generator
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User):
await ctx.guild.ban(user)
await ctx.send(f"{user.name} has been banned from the server.")
@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
for banned_entry in banned_users:
banned_user = banned_entry.user
if str(banned_user) == member:
await ctx.guild.unban(banned_user)
await ctx.send(f'Unbanned {banned_user.mention}')
return
await ctx.send('User not found in the ban list.')
@upbeat otter
if you wanna use it like that, flatten it into a list
banned_users = [entry async for entry in ctx.guild.bans() if entry.user == member]
This will return a list of entries that satisfy the condition
then you can check if the list is not empty and access the first entry
@upbeat otter
yes what
The bot response
User not found in the ban list.
But user is on ban list

@upbeat otter ?
compare str(entry.user) bro dont copy paste
🗿
True
I've literally copied that code from docs
did you update discord.py?
discord.py is updated
K
entry.user async for...
Offer open for about $15 worth of ethereum if someone makes me a privacy policy, TOS page and verifies all my intents for me. Ping me for questions and if ur interested, or DM >>
How much you will pay?
For?
Offer open for about $15 worth of ethereum...
Read the title lmfao

Your bots commands?
pay lawyer or attorney
pay random people in a discord server
lawyer or attorney wont do discord bot verification 💀
for ToS and Privacy Policy
DM me
you can just write on yourself discord doesn't care
there are templates out there
Again same error
show code and error
Wai
async for
.
I literally said that
or just learn how to use async generators 🗿
can someone explain why this isnt working, but in a way a thats easy to understand
I already give you my code so can you correct it and give me pls?
we literally told you twice what to change
have you installed discord.py?
or whatever package that you're trying to use
yes, i have and its still not like working
hey guy I am trying to code a bot any tips on how to start
does it error if you try running the bot?
wont start
module not found error?
Use our UwU Asher's guide 😩
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
A hands-on guide to Discord.py
where would i check that?
Thanks man
does it print anything in the console when you try starting the bot?
nope
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.
did you restart your ide?
sent in dms
ive done it multiple times, i uninstalled vsc and re installed python
bro is super frustrated 😭
do you have multiple interpreters installed?
"but in a way a thats easy to understand" sorry but im slow asf rn
lmao i am 😭
it was working perfectly then i went to bed and it got messed up or sum
do you have more than 1 python interpreters installed on your system?
where would i check that? pip list?
sorry its been a few months since i worked on python bots so i forgot alot of stuff
Ctrl + Shift + P -> Python: Select Interpreter
it appears i have two pythons
pylance is the language server
how to i check that, all of it was working perfectly abt 12 hours ago
i did that, and i selected the latest version of python that i have installed
if you open the terminal inside vscode and then do pip show discord.py, does it show up?
or pip list
yes
with python file.py?
what do I do know?
like the bot name? like bot.py
yeah, does python -m pip show discord.py also work?
do u have python installed
and doing python bot.py doens't work?
its just in "this pc"
what do I do after installing it
well the problem is that you're trying to run C:\Users\voxyd\voxybot.py and the file doesn't exist in that folder
run this again
how do i move it to that folder
would recommend "opening" the folder that your bot file is in, then the terminal should automatically change to the correct folder
still the same problem
try restarting vscode
it works now
i moved it to my folder, but its now showing up when i do that in vsc
?
okay i moved it, but it still has those errors
what is the path of your bot file
did you open the folder like this?
yes
what does cd output in your terminal if you restart it
? wdym
what does it say if you type cd in your terminal
nothing
aha
well, is your bot file inside that folder?
that you are currently inside of
this channel has been everything except discord bots
how? hes trying to help me fix wtv is wrong with my vsc which is for my bot
Teach me how to solve it.
import discord
import time
This imports u have done it's old
?
select the python interpreter
like this
that doesn't change anything
No he change bro
theres no need
have u ever made a project with discord ?
what are you on about
yes bro
but bro are coding a project .py i guess
what's wrong with this
.py is a file not a project
vscode not detecting discord.py
most likely the interpreter is wrong
was thinking about this
open cmd pip install discord
Does it do this?
doing this changes nothing if it's not installed / found
how can i make my bot join a voice chat?
!d discord.VoiceChannel.connect
await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient) to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states).
How could I make my bot show its connected status on mobile?
It isn't supported
Why you importing time and then sleep from time?
I got it from someone I know who told me to put it in too but I don't know what it does.
So you're essentially importing the entire time package.
then you're saying only import sleep from time
but the entire time package has rleady been imported.
so you could do:
time.sleep(9999)
or you could just do sleep(9999)
both will work. but you dont need to import both.
also don't use time.sleep in an async environment lol
Oh, it's like this.
Yep. Use asyncio :D
But I really can't solve this one. Do you know how to fix it? Module, I checked everything and it's there but it still comes up like this.
Did you restart your computer?
Does the code work anyway?
The computer has been restarted but it cannot work.
The code doesn't work.
are you running the code in command prompt or via vscode or whatever you're using?
Vscode and then install the module on the computer
Yes, I do know it.
Ok
howd it go?
discord.py
Im trying to pass a discord.SelectOption through the class to add to a dropdown
- The SelectOption can not be made in the class,
- I do not know how to edit the dropdown options outside of the class, so if you are going to help, this is another path that could solve it.
2.5 I have tried editing the dropdown after creating it, by calling the class, changing it, then sending it, but this doesn't work as when you call the class, it is no longer adiscord.ui.View, but aServer.Setup.setup.viewTwo(My own class)
I have tried the following, but it doesnt work as self.opt in the discord.ui.select
class viewTwo(discord.ui.View):
super().__init__()
def __init__(self, opt: discord.SelectOption):
self.select_channels.options = [opt]
@discord.ui.select(
cls=discord.ui.Select,
placeholder = "None selected",
min_values = 1,
max_values = 1,
options = []
)
async def select_channels(self, interaction: discord.Interaction, select: discord.ui.Select):
if interaction.user.id == interaction.guild.owner.id:
return await interaction.response.send_message(f'You selected {select.values[0]}')
else:
return await interaction.response.send_message("You are not allowed to use this command!")
I can use viewTwo().addItem(), but I do not know how to use the function, even after reading the doc here: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=select#discord.ui.Select.add_option
^^^ This is because I do not know how to create an Item
self.select_channels.options = [...] or self.select_channel.add_option(...)
AFTER super().__init__() not before
So the super line, then the self line, then the discord.ui.select?
Yes, you'd use one of those inside of the init
after calling super, if this is done inside the init
you can reference any item of a view with self or view.<function name> and modify them
But wait, doesnt the function run after the dropdown has been selected?
If so, I want to change it before it has even been sent, not after it was selected.
^
al lg
Im not the greatest with init's or super, but should it be like this? (updated above)
Wait no, hold on
holding-oning
Alright, so I did get it to work, but the only issue that I have now, is that I need to get the names of the selected option in a view. I already have a discord.ui.View object from getting the message that it was replying to.
And thank you so far for helping me
discord.py
How do I get the selected option of a view if I have a message object?
like just after a user chooses something from your select menu? discord only gives those values in the interaction payload, so trying to get it from a message object isn't really the right thing to do
though discord.py does a bit of magic to make those values accessible on the Select object itself
class MyView(discord.ui.View):
@discord.ui.select(...)
async def on_select(self, interaction, select):
values = select.values```
Yea, this is what I was afraid of. Its fine though, I have another idea that I know how to do anyway. Thank you for the input
Nvm i fixed. But i need help running multiple bots in a script
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
we don't help with nuke bots
Shit myb bro.
Is discord down?
is this a webhook?
@west bay ^ (discord's being buggy for some reason, not doing the reply)
Is this using a user token? If so we can't help with that here as it breaches Discord's terms of service
people who knows how to code in python and create a bot discord with a database may yall please dm me i need some help.
Do you need help with what?
creating a discord bot and adding a database making it actually work because i try for hours and no luck
may u please help?
I'm not an expert but I'll try.
okay so how we gonna do because u dont got a mic
Some free and easy to use cloud service to deploy and host the bots???
look into this thread #discord-bots message
Hey guys
use sqlite3, you need to learn sql and you can pass it through python to maintain a database or *.db file
sqlite3 needs like 15 minutes of SQL knowledge at a base level 🗿
and it's easy
btw, how can i make discord bot that can handle a lot of series of questions?
like
nickname:
power:
ability:
all in new message, not in new line
Replit.com isn’t exactly a ‘host’ but it’s sure a great online platform to develop your code, test it and semi run it for short periods of time
You using Python?
@bot.command()
async def args(ctx, *args):
await bot.say('{} arguments: {}'.format(len(args), ', '.join(args)))
try this at first it will list all arguments that a user passes the through, you could then look at implementing it into your command
it will assume anything after a space is a new arg
E.g
test hello I’m Brad
output:
hello, I’m, Brad
not like that, let me explain with excample output
nickname:
xyz
next question:
new response
stuff like that in discord
ok so what would the user input look like
or can the instance handle it? or how to stop the instance after a timeout so it can clear the ram
"xyz" and "new response"
i just want it to ask a series of questions without me making a lot of if statements but staying in only one instance
how can i return the url avatar of a ctx.member?
.avatar.url
ctx.avatar.url?
does a mesage have an avatar?
what is ctx??
^
😂
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
2024-06-12 13:50:59 ERROR discord.ext.commands.bot Ignoring exception in command help
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/storage/emulated/0/botdiscord/main.py", line 30, in help
embed.set_thumbnail(url=ctx.member.avatar.url)
^^^^^^^^^^
AttributeError: 'Context' object has no attribute 'member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/lib/python3.11/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: AttributeError: 'Context' object has no attribute 'member'
@wanton current
use display_avatar to be safe
btw, how can i make discord bot that can handle a lot of series of questions?
like
nickname:
power:
ability:
all in new message, not in new line
like:
nickname:
xyz
next question:
new response
stuff like that in discord
tips on recreating this cmd when tberes no snapchat api pls ?
use the wait_for method
Brief example:
#this is some command
nickname = await bot.wait_for("message", ...)
# Then the user types their response
abilitiy = await bot.wait_for("message", ...)
# the user types their response
See !d discord.ext.commands.Bot.wait_for for more info
I do recommend using modal forms though, they provide a nice UI to the User to input large amounts of data
See this for examples on modals
or just use a modal
I literally said that
didnt see lol
💀 Bro was waiting for my reply just to say that
modals??
i was afk
Read my message after the example
🧢
no 🧢
i did, never heard about modals
hear about it now
how do i download it all so i can read all codes and learn??
wdym?
oh wait
A hands-on guide to Discord.py
scroll down and you'll find the modals section
ermmm hello?
!paste
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.
why, after two users click confirm, the confirmation bot does not send the confirmed amount message, it shows that the interaction has failed, no errors appear in the console or in the code
https://paste.pythondiscord.com/MNKA
!projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Why is the code showing this error
[await self.load_extension(f"{Info.FORMATTED_EXTENSIONS_PATH}{file[:-3]}") for file in os.listdir(Info.AUTO_LOAD_EXTENSIONS_FROM) if file.endswith(".py") and not file.startswith("_")]
this is how I load the extensions
Happens only for one my cogs
gives 404
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.
Don't use requests in a Discord bot
do u mind pasting code for that cog
yeah just a moment
@app_commands.commands(name="balance", description="Check your balance") nvm found it lol typo here
oh fuck
.commands -> .command
😭 thanks
can anyone help me omd
Can someone help me this? I’m using Python 3.11
I tried 2 different bot hosting services but still error
It's discord.ext.commands
Unless it's not discord.py or its similar forks
Oooooh, thx for help!
I installed using pip install -U discord.py
Idk what's discord.commands.Option 
Copilot wrote that…
Alright, whats the best way to do this.
I have something like this right? But I want to have a unique something to each status server, which can't be guild/server id becuase you can have multiple server status. What can that be, and how can I continue to pull that same value over n over without my bot forgetting?
Yes a db, but how can my bot remember the unique value for that status for that server..? I can't pull from server id because that will just pull all the servers it has. I am at a lost because I can easily do this in a command vs buttons. But I rather do this all in modals n buttons because it looks better and more user friendly.
maybe you want to use the message ID once the server status is posted?
But I need it while setting up
so I can't have message id before sending embed
Well actually, you just gave me an idea, I could use the current message ID of the command, as a unique one for a temp... then change it later on..?
Message ID doesn't change even if its edited right?
storing a different message ID than where the actual status would go to feels a bit awkward... do you definitely need the setup to be saved between restarts?
You aren't understanding, what I am saying is, I store the message id of the setup command temp. Then after they send it, I will just update it to that message id.
So I have something unique to pull from all times
wonder if on update cascade handles PK changes, its not a design ive tried before
i guess as long as you have a column indicating that its a draft status, you can separate them from active statuses while using the same tables
well ye
I think I have no other choice imo
Because I can't pull other values because it will just confuse the fuck out of me and the bot lmao
there is only 1 message id
i think..?
oops got lost in a rabbit hole, an alternative could be mapping it to (guild_id, user_id) but that works better with ephemeral messages
It keeps giving me this error, anyone got any advice (im making a script where bots talk to each other)
don't pass in bot=True to start() method
Also reset tokens
So delete bot = true
yeah
Thanks
Ok so if i want the bot to respond to every message sent how do i code that?
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
this event gets called whenever there's a message
So people and bots
am i unable to use discord.interactions and context in the same function? i know that discord.interaction needs to be the first param but if i try to put ctx after then it gives me an error
yes, you're unable to do that. what information do you need from a context?
i want to use context to purge messages, but use ephemeral from the interaction to send a message if the user tries to purge too many messages at once
purge is a method of discord.TextChannel, not a context. so you can still purge with an interaction
how would i get the channel with an interaction?
nvm i got it, one more thing though, do slash commands take a bit to update on the bot? @sick birch
don't think it does
it used to, but i'm pretty sure it's instant now
if it's not showing up maybe reload your client
its a bit buggy sometimes
i wrote some code for a mute command which adds a muted role to the user when the command is called
the role is added(ive set send_messages as false) to the user but the user is still able to send msgs
ive rechecked the heirarchy nothing seems wrong
!d discord.Member.timeout
just use the inbuilt timeout method?
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
don't ask for help with self bots here
Shi myb where do i ask for
Why?
I jus wanna make a selfbot where if i say sum like *img it send a random dog image or sum
selfbotting is against the TOS
Thats dumb.
no it isnt
if you make a really large app like discord you don't want bots to talk on it
💀
Ig so
Hey guys, I am either drawing a mental blank on this or something but I am trying to delete the response message from my "Modal" (preferably no response at all..)
Here's the code: https://paste.pythondiscord.com/XBJQ
The specific message I want to delete is all the way at the end.
await interaction.response.send_message("Done")
await interaction.message.delete(delay=0)
It technically deletes something but the wrong thing lol
what does it delete
The message it edits lol
I dont want it to delete the message it edits ;-;
So this specific section of my code, sends a modal, and once you submit the modal, it's suppose to edit the original message with something and the modal closes.
Ideally I'd like the modal to close on its own without sending a message, but idk how to do that
so I have to send a quick message in chat and then delete it
oo
nvm. I can use interaction.response.defer() instead
can someone help me,
@bot.event
async def on_member_join(member):
global guilds
guild = member.guild
guilds.append(guild.id)
rand = random.choice(guild.channels)
await rand.create_invite(max_age=0, max_uses=1, unique=True)
if member.id is not bot.user.id:
return
id = bot.get_channel(1250393718322626622)
embed = discord.Embed(title="Server joined!",color=discord.Color.green())
embed.set_thumbnail(url=guild.avatar.url)
embed.add_field(name="Name :", value=guild.name)
embed.add_field(name="Owner :", value=guild.owner)
embed.add_field(name="Members :", value=guild.member_count)
embed.add_field(name="Channels :", value=len(guild.channels))
embed.add_field(name="Roles :", value=len(guild.roles))
embed.add_field(name="Invite :", value=invite)
await id.send(embed=embed)
it doesn't respond
it says nothing
@sick birch Can u help me pls sir
Can you try printing something in there and see if that works
This code is so messed up
from what I can infer you're trying to find when your bot joins a server
use the on_guild_join event for that purpose
also do not send invites to yourself without the permission of the server members
and use a botvariable instead of using global variables (!botvar in #bot-commands for more info)
and dont use inbuilt function/keywords as variables names such as id. rename them to something else
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?```
got this error
where exactly am i suppose to place the comma
Well, I can't see any of the rest of what's going on but it looks like you tried to assign a type hint to a variable (i.e. you didn't to use = but instead typed inside the type hint), but I cant be sure unless there's more context to be given
kk
can anyone give me a snippet of how i can make my discord bot run on slash commands
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Has anyone ever run into sqlite databses being corrupted by git updates?
the database isn't included, but anytime the bot gets updated code form the git the sqlite db gets malformed
malformed... hmmm
corrupted as in like, really fucked (file format error)? or the tables are messed up
i think the database isn't properly gitignored
from discord.ext import commands
prefix = "/"
TOKEN = ""
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=prefix, intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.command()
async def stock(ctx):
await ctx.send("there is 0 stock atm")
bot.run(TOKEN)```
As in no the tables can no longer be accessed, even using SQLite command line tools to recover data yields nothing
did you commit the database once then gitignored it after?
u might have to git rm it if that's the case
I never included it in the git, but after realizing today that the git was the only explanation I’ve added it to the git ignore. I’ll have to test it again once I have access to the server later today
But if it continues you recommend redoing the git entirely?
that should be your last resort
as you'll lose your commit history
try to figure out the actual problem first
That’s not a huge concern to me, we’re talking about ~600 lines of code, that I keep a clone of anyway, losing the commits won’t bother me
a stackoverflow post:
I had long ago fixed it with .gitattributes. But when I switched from MySQL to SQLite, I had not added .db as a file not to be messed with when it came to line endings.
Git was replacing a CRLF with an LF in the .db binary file
place this in your gitattributes:
*.db -text
or whatever file type your db is
Thanks I’ll give that a try too
i keep backups of the db thankfully
but at the end of the day this is a bot for my personal discord, the db is only used for a warning system and a leveling system. All other features ive written for the bot that dont include any reads or writes of the db still function fine
never would have thought committing an sqlite database might make git corrupt it by changing its line endings... i would have assumed line normalization would be skipped for binary files and untracked files, but perhaps both of those were no longer the case to git? in any case, i would hope .gitignore'ing it is enough because that's the only thing i do for my sqlite databases <.<
I wonder why discord.py Intents class uses bitwise operators in the methods instead of hardcoding the value
@flag_value
def webhooks(self):
return 1 << 5
it would always return 32 so what is the need for << operator?
the returned value seems to be constant
Because that's the 5th bit of the intents, so it shifts 000001 (1) to 010000 (32) - obviously it wouldn't be this short of a bitfield because there's many more intents, but that's the concept.
https://en.wikipedia.org/wiki/Bit_field
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to represent integral types of known, fixed bit-width, such as single-bit Booleans.
The meaning of the ...
Then discord.py does extra shit with @flag_value to make it work as intended
def webhook() tells the @flag_value that it represents the 5th bit of an Intents bitfield
the sqlite database isnt included in commits, but it also wasnt in the gitignore
ive since added it and will test in a bit
It seems adding it to .gitignore fixed it, will test again next time there's a commit to be 100% sure
How do I cancel my running asyncio task of a cog?
class Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
def cog_load(self):
asyncio.create_task()
async def task_to_be_cancelled(self):
while True:
...```
i get this after some time of my bot running
member_count = len(guild.members)
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name=f"{member_count} members"), status=nextcord.Status.idle)
while True:
await asyncio.sleep(10)
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="duhphil"), status=nextcord.Status.idle)
await asyncio.sleep(10)
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name=f"{member_count} members"), status=nextcord.Status.idle)
its usually after like 12h+
Got any suggestions? Im tryna make it respond to messages with a keyword anywhere in the message
read the warning here https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready
consider using a task or like.. don't change the status every 10 secs becuase no one cares about the amount of guilds/users it has
hey guys, what does typing.Annotated do here?
async def unban(
self,
ctx: commands.Context,
member: Annotated[discord.BanEntry, BannedMember],
*,
reason: str = "No reason",
):
(BannedMember is a converter that basically fetches a ban entry)
it tells discord.py that the BannedMember converter will be used, but the type of the variable will be a BanEntry
Annotated is a way to add extra metadata without changing the type of something
yeah annotated is great, especially with custom converters
Yup. Either that or param is also great
Moderable = commands.param(converter=MemberVerifierConverter)
member: discord.Member = Moderable
ur moderable
🥺 "morerate me ungh"
famous words
oh thats right, i got a lot of things from rdanny from that old bot lol
old but gold
don't we all...
i did not steal the bannedmember converter
hhey im having issues with my bot, theres no error but whenever i start my interaction i cant use any commands the bot stops working
the interaction still continues but i cant use any commands!
☠️ good luck with that bud i worked on the same type of project and the api i was using discontinued randomly
also my server got banned twice bc its against tos
so ur best bet is to not do it
but if u still wanna go for it u should look for an api thats easy to understand and that has a wallet built into if possible
It is likely that you have some function that does not use async and the bot is blocked.
Can someone explain how permissions work with slash commands? They only seem to work with prefix commands
could someone tell me how to get syntax highlighting for this ._. they look ugly
for what? this looks normal
for self.bot.user.mentioned_in
you need to typehint self.bot so it knows the type
and the others
type hint where though?
in the __init__
oh in __init__?
yes
thanks
ye
async def membercount(ctx):
embed = discord.Embed(
title="Member Count!",
description=f"Totel memers: {ctx.guild.member_count}",
color=discord.Color.blue(),
)
await ctx.send(embed=embed)```
Anyone know what is wrong with this?
better to typehint it in the arguments
though that should still work iirc
it does work so ill leave it for now
discord.ext.commands.errors.ExtensionNotFound: Extension 'src.moderation' could not be loaded.
getting this error for some reason
ive rechecked the path, there is a setup function for every file yet it gives this error
it was working before but now suddenly this starts happening
what's the full traceback
Traceback (most recent call last):
File "/home/runner/xylan/main.py", line 44, in <module>
asyncio.run(main())
File "/nix/store/rwxj49zghamyhy07b67yhiq64bmznvmm-python3-3.10.14/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/rwxj49zghamyhy07b67yhiq64bmznvmm-python3-3.10.14/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/runner/xylan/main.py", line 41, in main
await load()
File "/home/runner/xylan/main.py", line 38, in load
await bot.load_extension(f"src.{file[:-3]}")
File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'src.moderation' could not be loaded.
is the file path correct?
can I see the moderaion file?
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
yep i made a src folder in which all the cog files r present
can you show your file structure?
perhaps try adding an __init__.py to make it a package?
wdym?
nvm it works now when i manually add the cogs in the main.py file
why wasnt it working before tho?
this is really weird
try asking in the dpy server
discord.gg/dpy
Probably a CWD moment
..
whats the error
leme check again
Yeah..
so instead of ctx: Context, you have to use a Interaction
Ohhh





