#discord-bots
1 messages Β· Page 382 of 1
(you can also have external files that aren't extensions)
Actually?
Yeah basic python rules apply. You could very well declare a class (a cog) in another file and import it just as normal. Extensions are purely optional
doesnt work
i added await but the bot still doesnt send any message
I don't want to interrupt the current conversation, could someone let me know when they're free to help please
don't ask to ask
what do you mean?
you're asking to ask right now
you have to ask for the solution to your problem directly
i shouldn't even need to explain what i mean
I will, I just don't want to take the attention away from someone else
can you just ask really quickly
alright then
Error handling request
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\web_protocol.py", line 452, in _handle_request
resp = await request_handler(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\web_app.py", line 543, in _handle
resp = await handler(request)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chris\OneDrive\Programming\misc\discord_bot_server\main.py", line 48, in send
await my_channel.send(content="meow")
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 638, in request
async with self.__session.request(method, url, **kwargs) as response:
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\client.py", line 1197, in __aenter__
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\client.py", line 507, in _request
with timer:
File "C:\Users\chris\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiohttp\helpers.py", line 715, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
```I don't even know where to start with this
you see this? we wouldn't be having that conversation if you just asked
yeah i don't know anything about aiohttp
Solstice can most likely help
actually
can you send the code around line 57
yo. you have to do that outside of your Cog
ik but that doesnt work too
i restructured the code to try and fix the problem, and it didn't work so i put it back. so the (exact same) error is now line 48, so i'll send the function there
that's it
its what happens if i add it outside of my cog
you have to do that in a function, preferably setup_hook in the main python script
You shouldn't be adding the cog...inside of itself
ik
i tried adding it outside
what is the request parameter doing there?
but it just says this if i add it outside of it
bro i literally just told you that you can only use add_cog in an async function
can you just add that line to the setup_hook function
!d discord.ext.commands.Bot
the thing I'm trying to do that doesn't work is this. a thread is running a discord.py bot, the main thread is running an aiohttp server. when a http request is sent to the server, it calls the send function with the relevant request object. it tries to send a message and then... blows up for no good reason.
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2\.0\.
I strongly recommend you don't colocate these things in the same python process
sorry i don't know anything about multi-threading
how else is the server going to communicate with the bot? through files? lol
i still do really hacky code such as using Optional params so i don't have to do error handling π
my friend wanted a website that can control their discord bot. i don't see how else i'm supposed to link the two without having them be in the same process
it's not like i can communicate between processes over a local network because well... the entire obstacle here is that the discord process doesn't have a web server
it can be janky, i just want to get around this error
They do not have to be in the same process to communicate. This is the whole idea behind IPC
what's IPC
Interprocess communication
eh, maybe you can
So what is the web server doing, what is the bot doing, and what do they share
ty works
all I am trying to do is just make a demo script
web socket receives request, makes bot do something
alr
You don't even need to run a gateway bot to do that then
wydm
What about what you're trying to accomplish necessitates that?
I need this guy's English skills
because that is the end goal
The end goal is to receive request, do something. It going through a discord.py bot is an implementation detail, not a goal
You can do that if you really want to, though it should be through IPC
long-term goal: friend has a big discord.py bot that they want to build a web panel for
short-term goal: receive a request and then do something with discord.py as a proof of concept
can you give a specific example of "do something"?
_ _
web panels are common, but i find that for a lot of cases you don't actually need a gateway connection (and discord.py, by extension)
you can send messages without discord.py, relatively trivially
Yeah that could very quickly be done with a webhook
why is it your goal to tell me i'm a liar instead of actually helping me
i'm assuming you're looking for something like a texbox and a button on a webpage that sends a message via the bot
none of us are saying you're a liar, we are gathering more information to provide you help and alternatives in the best way
in software development there's usually more than one way to go about doing something and the context and situation call for different solutions that may be more optimal than others
can you give me the black formatter club house role
Huh?
nvm i didn't say that

they're just saying that the way you're trying to do it isn't necessary and there's other ways to do it
There is a pretty common phenomenon called the XY problem, where folks believe that the help they need is implementing the solution already in their head (X) rather than questioning it and taking a different approach entirely to the core goal (Y). To accomplish the material behavior you described, in order of what I'd recommend:
- Have the webserver internally do as much as it can, including communicating with the discord API
- If a gateway discord.py bot must be involved, have the webserver minimally communicate with it through some form of IPC and run these in separate processes
- Host both of these in the same process, where you will incur avoidable instabilities and maintenance problems. This would be done by attaching an asyncio-friendly web framework to the same asyncio event loop
surely you should at least respect someone's wishes and help them with X, given they probably have their own reasons for doing so, rather than patronise them by assuming they have no idea what they're talking about and must be an idiot who actually means Y
adding your own negative connotation to things, classical (i'm not allowed to say this)
Nobody said you have no idea what you're talking about. Us suggesting other things isn't that
People are wrong all the time and it's not a slight on their character. I'm in 11 years of industry experience and I get other solutions suggested to me all the time
Option 3 is how you'd do what you proposed, you will still need to invest time in learning and getting this to work to reach what's ultimately an antipattern
Why when I try to put the status of my bot online on Mobile it doesn't work?: ```py
source_ = source(discord.gateway.DiscordWebSocket.identify)
patched = re.sub(
r'(['"]$browser['"]:\s?['"
source_ = source(discord.gateway.DiscordWebSocket.identify)
patched = re.sub(
r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
r"\1Discord Android\2",
source_
)
loc = {}
exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
discord.gateway.DiscordWebSocket.identify = loc["identify"]```
@fast osprey
Can I please get a link to a tutorial on how to get started making Discord Bots? For complete beginners. Also for discord bots do I need to learn about async and concurrency?
Thanks!
When i group commands it don't show the sub command in server setting integration
It only shows the parent command is there any way to fix it?
Without removing the group
I want to lock commands with different roles
Another question I would like to ask is there any event which tells when the invite count increases?
Command groups are the level of permissioning. If you want to permission commands differently, they shouldn't be in the same group
I am thinking to build a bot any one want to collab with me ?
you just need a couple of eyes for that
Got it
π
what is it about ?
when uploading to a hosting server should i upload the py cache files?
or can i delete those?
pycache can be deleted, it's cache as the name suggests
many people prefer uploading pyc inside of zip file to your application though when doing to a server
(with optimizations)
as long as said zip file is properly appended to sys.path.
I think the pycache will be rebuilt if the server has a different os than local machines os
So you somehow know how long it will take to make but are unwilling to do it yourself
someone know how could i make the bot add a reaction to his embed right after saying it?
Is this for the purposes of people adding to that reaction to drive logic?
yup
I'd recommend you implement this with ui buttons rather than reactions
IMO the code is much cleaner on the handling side
If you're using discord.py, you can go to the repo and the examples/views folder
anyone know how to get max file size upload for discord bot attachments, i know its usually 25mb but sometimes it can be increased with boosts or something so is there a way to get actual max upload size
i do have a method if the file is too big but I prefer using discord attachments
!d discord.Guild.filesize_limit
property filesize_limit```
The maximum number of bytes files can have when uploaded to this guild.
I have a View where the user responds with a button. I'm trying to defer and then edit the embed in the message, but it sends a new message when I try to followup? How can it be made to edit the original message?
followup is for sending new messages
you can defer (non thinking) + edit_original_response
Ah, thanks!
If I want a database (a class instance of a custom Database class) to be available to all commands, is there a standard way of doing that in discord.py?
im not sure of a standard practice (dpy doesn't provide a DI framework), but my preference has been subclassing Bot and passing that to cogs / views / etc.
you could also write Context[Bot] and Interaction[Bot] to typehint ctx.bot and interaction.client respectively, in case you find yourself only having those available
iirc for Context you can override Bot.process_commands() and use the Bot.get_context(cls=) parameter to replace it with your own subclass, but interactions don't have an equivalent method, so it's probably best not going that route
I personally just have a separate database class and use that class everywhere instead of passing it through bot so that I can interact with the database in places where the bot instance isn't available / has to be explicitly be passed.
I have the db connection object as a class attribute and it's set up when the bot starts instead of having it as an instance attr
You can just attach something to the bot instance and then just access it anywhere you have the bot (which is pretty much anything in your application)
Do you people do CI / CD for your discord bots?
How is stuff attached to the bot instance?
Same way you attach anything to any object. Just something.whatever = something_else
not a good host for them LMAO
I do have a question that is more so out of curiosity rather than anything else. What's a discord bot you think is very complex to build and that would be impressive if you saw someone actually implement it?
Yeah, but only limiting/formatting/building docker images
no tests (:P) or CD
thanks
mine is deployed in kubernetes so CD would probably be a whole thing to work out
though i hear good things about argoCD...
That's really interesting. Do you have any resources that talk about doing the DevOps side of stuff for discord bots? Because I don't know either of these technologies. I asked because it was something mentioned several times on some websites.
it shouldn't matter. for the most part devops doesn't concern themselves too much with the actual applications
hence why we have stuff like docker that abstracts it out
i need someone to help me
you should ask your question then
need help making custom web hook bot
thanks for the insight
Very interesting question, I would also like to hear about this
i'm not sure you can entirely making just the discord bot itself very interesting, discord bots are a type of frontend (albeit a very limited one), your code that is handling it the "backend" so IMO most of the interesting and complex stuff goes on there
Ok, I understand what you mean.
So maybe having the bot interacting with databases or APIs? I'm a beginner, I don't know what other interesting backend things are there
maybe. though stuff like that is super common
is it possible to upload image on role with memory buffer?
sure, according to docs Role.edit(display_icon=) simply takes a bytes object
How do i make my discord bot detect if the command was sent with a file attached?
u can check the content of it
Yeah and im asking how do i that?
slash command or prefix command?
prefix
also how do i make it download the file?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
gives you a list of attachments in a message
however i believe you can use it as a typehint argument
^ if its discord.py, you can add a parameter typehinted with discord.Attachment to automatically retrieve it for you
its included in their commands guide
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#discord-attachment
huh. maybe that needs a docs change?
hmm yeah probably an oversight, wasnt included in changelog either
i tried that but it always gives an error
can you show us your code and the error that was generated?
@client.command(pass_context = True)
async def download(ctx):
if not str(ctx.attachments) == "[]":
#file downloader here
await ctx.reply('File downloaded.')
else:
await ctx.reply('Attach a file to download.')
the first argument in a prefix command is a Context instance which doesn't have an .attachments attribute
if you want to check the attachments, you should access the message from the context object first with .message, then get the .attachments from that
ctx.message.attachments ?
yup, like: ```py
if len(ctx.message.attachments) < 1:
return await ctx.reply("Please upload an attachment!")
first_attachment = ctx.message.attachments[0]
... ```
as for downloading the data of the attachment, you can pick from .read(), .save(), and .to_file(), depending on what you intend to do with that data afterwards
i intend to save it to a folder
in that case .save() would be the most convenient method
!d discord.Attachment.save
await save(fp, *, seek_begin=True, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this attachment into a file\-like object.
ergh, that doesnt mention it accepting a filepath
well you could either open a file first or pass the filepath as a string, as in: ```py
with open("my_file.png", "wb") as f:
await attachment.save(f)
or:
await attachment.save("my_file.png")```
Attachment also has a .filename attribute defined by the uploader if you want to use that
first_attachment = ctx.message.attachments[0]
await attachment.save(/home/user/pythonprojects/bot/str(first_attachment))
would something like this work
with proper quoting and formatting sure
using str() on an Attachment gives you the url though, not its filename
do you use vscode or pycharm? an editor with type checking and autocompletion would help a lot in writing your command
i use vscodium so yeah
hmm, in your case i think you can get the basedpyright extension as an alternative to microsoft's pylance
ok ill install it
in the settings you should be able to change the "Type Checking Mode" to basic or standard if you find the default is too aggressive/noisy
at least, it should warn you of syntax errors and undefined variables or methods
https://discordpy.readthedocs.io/en/stable/api.html?highlight=edit#discord.Role.edit can it take url and updae it
!d discord.Role.edit if display_icon is not supported by guild will it raise error or just become None?
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to do this.
All fields are optional.
Changed in version 1\.4: Can now pass `int` to `colour` keyword\-only parameter.
Changed in version 2\.0: Edits are no longer in\-place, the newly edited role is returned instead...
Guild boost lvl 2 allow us to add emoji right if I check that before adding role_icon i think I can skip the error
Or is there any efficient way?
erm, just use guild.features, if 'ROLE_ICONS' in guild.features:
Tried that, but my linter complained that bot.db isn't a thing on a Bot instance. Anyways, that's not really discord.py specific
Bro I need help
the way i solve it is like so: https://github.com/vipyrsec/bot/blob/main/src/bot/bot.py#L57-L61
I was following the tutorial how to implement chatgpt in a discord not.
src/bot/bot.py lines 57 to 61
def __init__(
self: Self,
dragonfly_services: DragonflyServices,
*args: tuple,
**kwargs: dict,```
so the linter knows the type when it's set
i think this may have been mentioned but making a global instance and importing it around will also work
Lol not decided but once I find partners I will decide
think of what you are creating first rather then looking for ppl
Um actually I can work in any projects like web or bots
But I m too much confused
is it possible to automatically add image to role with file?
wdym by "automatically" and "add image to role"
i am getting buffer and i want to use that buffer to add image
to a role
that explains nothing
i solved the issue , discord.py server linked me the resources
how to remove thumbnails from Embeds
i want to remove my gif thumbnail on a condition
Edit the message and send a new embed to it which doesn't have the thumbnail
!d discord.Embed.set_thumbnail take the embed object and pass None to url
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent\-style chaining.
Changed in version 1\.4: Passing `None` removes the thumbnail.
this will remove the thumbnail
I mean, I inferred they meant they want to remove the thumbnail after sending the message, in which case they will need to edit it too with an embed with no thumbnail
how do i send the user a dm saying that theyve been kicked from the server? i use discords built in kick command, not a custom kick command
code: https://pastes.dev/GmER1VLPFB
its in hikari-py
i tried making my code work but it says it cant dm the user
You can't dm users who don't share a server with the bot. It is also against tos to dm users who have not explicitly asked you to
?
its not against tos for a discord bot to send a user a dm saying that theyve been kicked from a server lol
It is against tos to dm a user who has not given you permission to
Sorry, developer policy.
- Do not contact users on Discord without their explicit permission.
how can i send a local image to discord using discord.py in the embed
that user should disable their dms and this rule should be removed
The onus should not be on users
anyone can help?
Hi so I've made a command with two args, of "ticket" and "name", that lets ppl move channels but for some reason it won't work when omitting the "ticket" arg when used n the context channel
@commands.bot_has_permissions(manage_channels=True, manage_roles=True)
@checks.in_database()
@checks.is_mod()
@commands.guild_only()
@commands.command(description="Move ModMail ticket to new category.", usage="moveticket <ticket> <name>")
async def moveticket(self, ctx, ticket: discord.TextChannel=None, *, name: str):
ticket = ticket or ctx.channel
if checks.is_modmail_channel2(self.bot, ticket) is False:
await ctx.send(embed=discord.Embed(description="That channel is not a ModMail ticket.",colour=self.bot.error_colour,))
return
async with self.bot.pool.acquire() as conn:
res = await conn.fetchrow("SELECT category FROM categories WHERE name=$1 AND guild=$2", name, ctx.guild.id)
if res is None:
await ctx.send(embed=discord.Embed(description="The name provoded doesn't match any ModMail category.",colour=self.bot.error_colour,))
return
category = ctx.guild.get_channel(res["category"])
try:
old_category = ticket.category
await ticket.edit(reason = f"{ctx.author} moved ticket {ticket.name} from {old_category.name} to {category.name}",category=category,sync_permissions=True)
await ctx.send(embed=discord.Embed(description="The ticket was moved successfully.", colour=self.bot.primary_colour))
except discord.Forbidden:
await ctx.send(embed=discord.Embed(description="Missing permissions to move the ticket.",colour=self.bot.error_colour,))
I thought maybe discord.TextChannel was having an issue (I am using dpy 1.5 after all) So I changed it to the following but that hasn't worked either
async def moveticket(self, ctx, ticket: int=None, *, name: str):
try:
ticket = ctx.guild.get_channel(ticket)
except discord.NotFound:
ticket = None
if ticket is None:
ticket = ctx.channel
if checks.is_modmail_channel2(self.bot, ticket) is False:
anything less than 2.0 isn't supported, and will get api outages
i'm aware π the 16 odd bots I have running on this version haven't seen any major issues.
I'm just not sure why it's not able to make the ticket arg optionable
There are literally api blackouts where it won't respond
That should concern you more than one specific command not working sometimes 
Anyways, a little debugging to identify the line that's not behaving like you expect would be useful
The problem is I don't know what line specifically is causing the problem, I'm pretty sure it's something to do with how the ticket arg is being handled. It's like the code isn't able to check if ticket has a value or isn't able to set it with a new value if ctx.
like you want it to assume the user typed in the name if the first argument isn't a valid channel? seems 1.5 still has the Optional converter, so you probably want that
https://discordpy.readthedocs.io/en/v1.5.1/ext/commands/commands.html#typing-optional
Sort of.
If a user doesn't type in a valid channel then I want it to set the channel/ticket arg to the context channel, the channel where the command was used
sure, Optional + your reassignment at the start of the command would be fine for that
I thought ...=None would have been making it optional?
I'll add optional to it when I'm next at the laptop and feed back on my result
the difference is subtle, but only Optional allows the parameter to be skipped during dpy's parsing
just writing a default value doesn't have the same effect
= None does make it optional. The Optional typehint is, well, optional
does it also let you skip that argument but still supply the other arguments following it?
I always thought it did
Step one in debugging would be to log the parameters you are getting to make sure they are what you think they are
is there any method which takes invite code and retrives the full invite link?
i think appending the invite code after discord.gg/ will cut it
discord handles redirection
Hi here
im using discord audit log to log im text channel but moderator action are not showing
i did try this
@commands.Cog.listener()
async def on_audit_log_entry_create(self, entry: discord.AuditLogEntry):
async def default_handler(entry):
pass
print(f"New audit log entry: {entry.action}")
but nothing printing out
in doc its says that i need This requires Intents.moderation to be enabled.
but when i do intents.moderation = True
i get AttributeError: 'Intents' object has no attribute 'moderation'
im using intents = discord.Intents.default()
and i did try using all and none
What version of the library are you on?
latest
Which is?
2.1.0
That is not the latest (for discord.py at least)
Requirement already satisfied: discord.py in c:~\python\python311\lib\site-packages (2.1.0)
when i try to update
How are you trying to update?
pip install
thx for ur time
can someone help me how i can make bot to give roles when someone writes one message in verifiy channel?
thanks guys
What are you verifying by doing so?
sorry for late answer
so for an example user join server and i leave one channel and its verifiy
and when he writes something there he get role
and then with role he get acess to other channels
Right, but what is that message intending to verify? That they've read rules?
There are native onboarding tools that would be more appropriate for that
Can anyone possibly help with this? ;-;
https://stackoverflow.com/q/78766545/17726391
Please tag me if anyone knows the answer ^^
Audio receive is unstable and not supported by the library (or discord itself)
hello, I want to make a discord bot using python. I need to somehow install discord.py but can't understand how. I tried some things but nothing works, please help me with that.
What did you try and what happened?
I'm watching a video and the guy there types pip install discord.py
when I try to run this command it gives me syntax error in "install"
And I have checked pip when installing python
I firstly recommend you stop watching videos, they are notoriously bad
oh okay, what should I do then?
If you're running on windows, just running pip x isn't ideal since it's ambiguous what python environment this runs against if pip is even on PATH at all. It's recommended to use the py launcher for everything python related
Either that or run everything within a virtual environment (preferred but more setup)
Python is on your system. Visual studio just runs against a specific installation if you hit run
But if you type pip x, you still run into exactly what I described
python launcher? what's that? I think it was installed with python but I'm not sure what that is exactly
So youβre saying I probably shouldnβt continue trying with multiple people? A single person works very well
py launcher. Literally just typing py on your terminal/command line
Ex py -m pip
This should be an option when installing python on windows and it's highly recommended as python environment management without it is ass
it says invalid syntax under pip
It's up to you, just that you won't get support from the library maintainers and discord is within their rights to completely break it with no forewarning or promises of replacing it
What are you typing, and what exactly is the response?
Where are you typing this? What happens if you just run py?
This is a command you'd put in a terminal. Not python code
ah, the cmd?
Yeah this looks like a python interpreter
If you want to run py, that's just done in a raw terminal
Not within the python interpreter itself
@fast osprey can u help me
I'm sure lots of people listening could as well
Feel free to ask your question(s) and if anyone knows the answer they will
import subprocess
import sys
they wont import for some reason
How to make bot when user join the server he must write one message in verify then he gets role
I would suggest you use the built in onboarding tools if you want users to acknowledge rules or ensure they've read something
What is leading you to believe that they aren't?
no i meant like when user join the server he has no rules and only one acess to verify channel and its supposed to be write something abt yourself and when he writes anything and send then he should get the role
@fast osprey can u help me to do it free? somewhere
Do you have any prior experience with discord.py or any fork?
You can do that with the onboarding tools, that's a built-in "task"
nope thats a problem i dont even know where to put code if u give me
i have no clue
Then that's a dead end
yh i guess but is there any chance that u could explain it to me?>
Well even for explaining you would need to have at least a beginner level understanding of python
I strongly suggest you start with exploring the onboarding tools already available to you
i could try atlesat to do it
its a thing that i make code put id channel token of bot and run the code or?
and i heard something that u need to host bot somewhere hosting ig
Yes u will need to host it
Well it's not as simple as u making it look
I'd say take a few courses of python
It's pretty easy to learn
how much does it cost?
Depends entirely on the resources the bot requires
@fast osprey @turbid condor @client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'give me admin':
role = get(message.guild.roles, name='role')
await message.author.add_roles(message.author, role)
like this?
yh shit is pretty hard i would appreciate if someone could make it work for me because i really need this today and i dont know how to do it
sure
what if i want to remove two roles from user and 1 role is present 1 not on user will that erorr out?
how can i know which role got removed?
from user.remove_roles?
Look at the audit log or compare the member roles before and after
member*
Still waiting lmao
Just see which role is present in the member in the first place and you can figure out which role has been removed https://discordpy.readthedocs.io/en/stable/api.html?highlight=member#discord.Member.roles
i know how to find roles i am trying to figure out which roles has been removed with remove_roles
Yeah, see if the roles you're trying to remove exists the member, if it exists means that role is removed, if it doesn't exist that role isn't removed from the user
Sup
Can someone tell me how to correct this code?
voice = discord.voice_client.VoiceClient
source = FFmpegPCMAudio(dir_path + sound)
player = voice.play(source)
Im trying to play an audio file.
i didnt forget
from discord import FFmpegPCMAudio
btw
i just dont know what to put before .play()
as voice
Fixed
I have a question, how do i get the voice channel that the discord bot is in?
solved.
how can i add error handling to my bot's ban command??
like i dont understand how you could do like if the discord.Member is None but also the modreason
im so bad at python so if someone could help me i would greatly appreciate it
What is this ban command doing? Is it just a wrapper over a person manually banning a single user? If so, you should really consider not implementing this as you are actively reducing the security controls on the ban command that already exists natively
no error handling??
I'm suggesting you don't have this command at all as it is actively harmful to users
There is a native /ban in the client already. It has security controls that I guarantee your implementation does not
so are you saying don't do a ban command or jus don't do the error handling
I am suggesting you don't make a command that only exists to replicate what already exists but less secure
hmm i never thought about it that way
There are cases where you would have a more complex bit of logic over banning, but a direct "I run command person gets banned" is not that
ig yehh
The main reasons why you wouldn't want to do this are audit log hygiene and 2FA requirements, which bots really don't have a good way of replicating
thats true
is there a way I can sync my bot's commands to 2 or more servers without syncing globally or being rate limited?
!d discord.app_commands.CommandTree.sync I think this has a guild parameter
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
remember that the command also needs to have the same guild set
Why wont my pip install discord.py work?
!dashmpip probably π
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Cool thanks
I see this, but is it possible to have more than one guild be synced to? Would running the command once for each guild not get me rate-limited?
Have you gotten rate limited?
no, i havent tried it
There is very rarely a case where you would want to sync a command to multiple guilds but not all
syncing a command globally takes a few hours doesnt it?
Nope
i believe it used to but it doesn't appear to anymore
Has been a year+ since it's been noticeable
oh, something wrong with when i synced it then probably since I still havent had them show up π€ ill just need to do some fixes to the code then thanks
Two very important debugging tools:
- sync() returns the list of commands that got synced
- the integrations tab on a server will definitively tell you what commands are on a server, sometimes your client will lie
oh awesome thanks
So I fixed the sync and the commands show in the Integrations tab; do I need to wait longer to see them in chat? they dont show up with autocomplete
Refresh your discord client (ctrl + r)
tyyyy
can't see what the problem is if you don't share the exact actual error message
that line is not supposed to be in your code. You're supposed to run that in your terminal. Outside of the code
All raw event uses caching?
The opposite, the whole idea of raw events is that they're independent of the cache and just give you the raw payload
I was wondering how I can make a check to see if a channel is a ticket channel
I'm not sure what you define as a "ticket channel" but you can implement checks: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
What API wrapper do you recommend?
probably discord.py, just because it's got the most community support so it's easy to find help if you need it. you're free to use something else that suits your project though
Whats wrong with this? https://paste.pythondiscord.com/GN4A
what makes you say something is wrong
When Iβm using the limit parameter itβs responding with a actual number but when i use the after parameter itβs responding with 0
I mean we don't know what's in that channel, it might be helpful to do some logging in that loop to see what's actually happening
If you're using a channel as a database, I strongly recommend you use an actual database anyways
if msg.content.startswith('hello'):
print(msg.content[2])```
I need this to print out the second statement after `hello -> world <- This`
So I tried doing `msg.content[2]` to get the line of text after the first space, but seems that python does not work like that, and instead of giving me what I looked for it printed `e` (the e inside hello).
Can someone help me figure a way to do this? Thanks.
If youre using discord.py, I highly suggest you use the command framework for reading messages and parsing inputs
Why?
Do you mean the @bot.event / command() thing?
The command specifically yes
I'm using the 'event' for checking messages. I didn't write it above, but I have it in my code.
@bot.event
async def on_message(msg):
if msg.author != bot.user: return
if msg.content.startswith('$with'):
print(msg.content.endswith)```
I would recommend you do this with a command
Ok
And not use on_message at all
Because it will check all messages sent in the server?
Oh that would actually solve the issue because I remember bot.command() makes it easier to check the message's content without the trigger
Because it interferes with the command logic
Yeah, thanks.
Shard ID None session has been invalidated.
anyone know what can cause this error ?
as my wifi is not bad idk how to fix
i want to load one cog only if bot is ready
what is stopping you from doing so?
i dont know the method
what should i use?
one cog has lots of listners
do you know how to use cogs?
yeh
so just do that
i just want to make the cog wait
until bot becomes ready
then load it
is their any method which holds the cog initilization until bot becomes ready?
why does your cog need to wait for bot to be ready?
you said it was all only listeners?
when bot logs in bot class tries to contact api and takes token and attach that instance to itself and i am not able to use that instance bcz cog load before that
so if cog wait until bot gets ready then it can solve the issue
i'm not understanding, this doesn't seem like something that's dependent on your bot being ready
i am not able to use that instance bcz cog load before that
i dont understand this part
oh are you contacting the API in on_ready?
class MyBot(commands.Bot):
def __init__(self, *, intents: discord.Intents):
super().__init__(
command_prefix="supersecretjutsu",
help_command=None,
intents=intents,
tree_cls=CommandErrorHandler,
)
async def setup_hook(self):
coc_client = coc.Client(key_names=DevCreds.DEV_TOKEN_NAME)
await coc_client.login(
email=DevCreds.DEV_SITE_EMAIL, password=DevCreds.DEV_SITE_PASSWORD
)
self.coc_client: coc.Client = coc_client
this dont work in cog coc_client if bot dont become ready
async def setup_hook(self):
coc_client = coc.Client(key_names=DevCreds.DEV_TOKEN_NAME)
await coc_client.login(
email=DevCreds.DEV_SITE_EMAIL, password=DevCreds.DEV_SITE_PASSWORD
)
self.coc_client: coc.Client = coc_client
await self.add_cog(MyCog())
MyCog can now use coc_client
i fixed it
great
tnx robin
How can I check if there are any integers in a certain message sent?
Can do this pretty cleanly with regex on the message content
le bhaiya omfoo
i forgot to enable application.commands
now i have to make my commands like this
π
?
what do you mean '?'
what does that have to do with applications.commands
because that is supposed to be enabled to use bot commands
and i didnt when i invited it to test
so i spent 2 days making that system
think applications.commands is granted by default
no it is not
and you only need it if you want to create application commands i.e. slash commands
it is required to use it
then re-invite your bot with it
well i already made the system
i'd rather use it than ditch it for a new one, even if it's better
okay then
Hello, I need to find a way to execute a piece of code when my bot joins a server.
And also leave if it doesn't have all the permissions required. How to make this function?
@commands.slash_command(name="restore_verification")
async def restore_verification(self, inter: disnake.ApplicationCommandInteraction, user: typing.Optional[disnake.Member] = None):
await inter.response.defer(ephemeral=True)
main_guild = inter.guild
if user:
target = await main_guild.fetch_member(user.id)
print("28", target)
else:
target = await main_guild.fetch_member(inter.user.id)
print("32", target)
print(target)
target_roles = target.roles
print(target_roles)
verified = False
for role in target_roles:
print(role)
if role.id == config.verified_role:
verified = True
break
if not verified:
role = main_guild.get_role(config.verified_role)
await inter.edit_original_message(f"You do not have the {role.mention} role, you can't use ``/restore_verification``!")
return
user_roles = self.roles.find_one({"user_id": target.id})
for role in user_roles['obtained']:
if role in config.verification_roles:
await target.add_roles(main_guild.get_role(config.verification_roles[role]["Id"]))
print(config.verification_roles[role]["Id"])
await inter.edit_original_message("Target has been given all the roles they've been approved for!")
It returns None type object whenever I try to get the target's role, i have intents set up as disnake.Intents.none()
How to write discord badges like this?
The badges use custom emojis
How to find usr's badges and change the text to emojis...
It's up to you to find/choose the emojis
As far as badges, only a subset are exposed to bots
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
hi, im stuck on something on my bot, it doesn't show commands, i've always been strugglinh with it
imma send the main.py
here, also i want to load file from cogs folder
@commands.slash_command(name="restore_verification")
async def restore_verification(self, inter: disnake.ApplicationCommandInteraction, user: typing.Optional[disnake.Member] = None):
await inter.response.defer(ephemeral=True)
main_guild = inter.guild
if user:
target = await main_guild.fetch_member(user.id)
print("28", target)
else:
target = await main_guild.fetch_member(inter.user.id)
print("32", target)
print(target)
target_roles = target.roles
print(target_roles)
verified = False
for role in target_roles:
print(role)
if role.id == config.verified_role:
verified = True
break
if not verified:
role = main_guild.get_role(config.verified_role)
await inter.edit_original_message(f"You do not have the {role.mention} role, you can't use ``/restore_verification``!")
return
user_roles = self.roles.find_one({"user_id": target.id})
for role in user_roles['obtained']:
if role in config.verification_roles:
await target.add_roles(main_guild.get_role(config.verification_roles[role]["Id"]))
print(config.verification_roles[role]["Id"])
await inter.edit_original_message("Target has been given all the roles they've been approved for!")
It returns None type object whenever I try to get the target's role, i have intents set up as disnake.Intents.none()
im by no means good at python in any way but for my bot i tried it like this and it seems to work
cogs_directory = os.path.join(os.path.dirname(__file__), 'cogs')
for filename in os.listdir(cogs_directory):
if filename.endswith(".py"):
await client.load_extension(f"cogs.{filename[:-3]}")```
thx i'll try that
lemme know if it works
ye dw
I strongly recommend using pkgutil rather than looping over the file system yourself
okay
nope doesn't work
dam
it doesn't show on my discord server
sorry bro
dw
oh what the bot isnt online??
i checked ur server and its not online
rn it is
ohh
try doing some print statements
well i do that so everytime i boot up the bot it tells me the cogs r working
but its fine
i hope u figure it out 
What do you mean by "doesn't show"
like when i do "/" the commands aren't here
maybe its something to do with the commands??
wait it says the prefix is !
ye
but did u manually make the commands into slash commands too??
maybe jus try the commands with !
hmm
yehh idk
im not very good at python so im not too sure
it looks like it should work tho
ohh wdym
lemme try to out them from folder
do u mean like the slash commands work in the main code but not in cogs??
ye
cuz i have that too if thats what u mean
OMG
i jus did my slash commands in the main one cuz i only have /ping and /help
idk why discord cant jus make it easy
why everything in one file like f- it
like why cant we jus say like yo @discord when the user does /ping then show the ping!!
BOOM
ye true
yehh
should i switch to js?
there is prolly a way to make it work but idk
prolly
its harder but much faster response times and more community like help and stuff
ye
cuz its more common
yeah
im jus too stubborn to use js
i think coding discord bot is hell in python lol
yehh
worst thing ever
imagine if its hell in js too
lol
like imagine if coding discord bots is jus hell like however u do it
ye
i might jus give up on mine icl
thankfully nodejs is easier for common peopls
anyways good luck with ur bot bro
thx u too!
yehh
see ya men
adios
Can anyone help me with this?
Are you calling your sync? Are you logging what sync returns?
can anyone help me create a countdown bot that stays in a vc 24/7 and countdowns like this: 3 minutes till countdown
2 minutes til countdown
1 minute til countdown
30 seconds till countsown
10
9
8
7
6
5
4
3
2
1
Go
Please help me with this
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, "minutes till countdown")
time.sleep(60)
t -= 1
print("1 minute till countdown")
time.sleep(30)
print("30 seconds till countdown")
time.sleep(20)
print("10 seconds till countdown")
for i in range(10, 0, -1):
print(i)
time.sleep(1)
print("Go!")
# Start countdown for 3 minutes
countdown(3)
It's a bit unclear what you want to actually happen. Like it sends audio at those times?
yes i want it to speak like countdown in 3 min and etc what i said and then i want it so repeat the smae thing over and over afain endlesly but i want 30 sec between end of script and start
Do you have the sound files you want to play?
nah sadly not cuz im on vacation but i guess eleven or i forgot name but there you can create the sounds
could you hepp ne
Your init constructor has to have different parameters for it to work
Give me a moment let me look in my GitHub repo
You have to add the β/β parameter
That is not required
Really?
Yeah try it
Canβt, Iβm not at my computer
I forgot to do self.bot smh
If anyone is bored and got literally nothing to do and would want to do something feel free to create a countdown bot for me that is talking in vc like this: 3 minutes til countdown
2 minutes till countdown
1 minute til countdown
30 seconds til cluntdoen
10
9
8
7
6
5
4
3
2
1
Go
30 sec wait time till repeat
Pls help me with this bot i need it for my server. It will pop off ong
Dont rpely if u js gon say no one gon do it pls
I need this person who can do it so pls help me when ur bored
please dont crosspost your question in multiple channels
first of all make several audio files
if you know how to play sounds, and sleep, then you can do it
huh
ok can you connect a discord bot to a voice channel
wait what was the comand
ok i'll just send the docs https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegPCMAudio
bru im on phone and on website and not on dc real app bc itβs glitching for me
what i do witg the docs
bro im a npcs that don know shi
They're just asking for someone to write something they want entirely for them for free, not help
i'm not sure, i think you're supposed to just stare at them blankly
mhm π
but i dont understand what u mean with this
would you understand if i said "do you know how to do x"
no
but like
why is it so hard to just get a bot that can clintsown like i want in a vc
24/7
idk, i think it's because you don't even know how to connect a bot to a voice channel
how are you going to play audio if the bot isn't even in a voice channel

you cant
is this a good code for a bot to countdown as i want?
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, "minutes till countdown")
time.sleep(60)
t -= 1
print("1 minute till countdown")
time.sleep(30)
print("30 seconds till countdown")
time.sleep(20)
print("10 seconds till countdown")
for i in range(10, 0, -1):
print(i)
time.sleep(1)
print("Go!")
Start countdown for 3 minutes
countdown(3)
No
whats wrong with it
first of all, don't use a while loop, use a background task
Really
also, you're using time.sleep
Could you rewrite it lol
Dreamer already gave you a good starting point
he was just giving you an example for a synchronous program
Let's get this out of the way. Do you have any desire to learn and experiment, or are you going to keep asking until someone writes the whole thing for you for free
i wanna learn but ive tried before and it never works
it's because you're not trying hard enough
wym
i had 2 books that i read and i copied and followed the book but 1 week after i still aint learn nothing besfirs like hello world
and i never learn what like if and else and those key words what they mean
i cant leadn, its like i have a learning disability
wait. so you're trying to make a discord bot without knowing python?
you're only slowing yourself down by trying to get us to write your code
ye but like ive tried leafning by book and nothing witks
learn by writing code, not by following a book
There's no way you're going to do this without fundamental python basics. Your options here are:
- Put in the time to learn and experiment, there are plenty of resources but this is on you
- Go to a freelancing community and pay someone to build the thing you want
- Beg someone to make it for you for free (this isn't going to work and is just going to piss people off by you not valuing their time or skills)
it's like in physics, memorize the entire 1000 formulas right?
that's wrong. memorize 3 formulas, understand what you're doing, and only use those 3 formulas for the rest of your life
Then refer to option 2
have someone study with you
python has a really easy syntax as long as you don't touch #esoteric-python
yes ive tried dozens of times but i never learn so it gets boring and thten i quit
Me and my dad created a game just like snake
Programming is not the kind of thing that is straightforward or has immediate yields. It requires patience and resiliency.
yes i figured
if you quit at any point you're not trying hard enough
practice your fundamentals
it's like math, you can't learn pre-calculus if you don't even know pre-algebra
you can't do AP physics 1 if you didn't even finish algebra 1
yh
in boxing, you can't do a professional fight if you can't even throw your 6 basic punches correctly
can you do a 540 tornado kick if you can't throw a roundhouse?
ye ur righy, im jusg looking for stuff the easy and wuick yway
trying to do things from the top is the quick and really hard way
There is no easy and quick way
you have to start from the bottom
idk i kinda just solved problems after learning what everything does and how it works
no i solved problems such as - 3 5 = -2
i believe this is called "prefix notation evaluation"
Prefix notation is a mathematical notation. It is a way to write down equations and other mathematical formulae. Prefix notation is also known as Polish notation. The notation was invented by Jan Εukasiewicz in 1920. He wanted to simplify writing logic equations.
When prefix notation is used, no grouping elements (like parenthesis) are needed.
W...
wth is that even lol
- 3 5 is the same as 3 minus 5
nah, some CS graduates weren't able to solve it when my teacher interviewed them
it is an easy problem though
now that u said how to do
it was easy, can u say another one similar to that ine
wait wait u solved that problem coding?
yes.
you should find a project that is both within your skill level and has use to you
this is the optimal way of learning
this is what i usually tell people when they ask others to suggest a project for them, you know yourself better than we do and you can pick a project out for yourself based on your interests far better than we can
ye well my skill is at 0 lol
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
serious? this server had a resources page the whole time?
A Byte of Python and Automate the Boring Stuff come highly recommended
if i dedicate myself rlly much to learn would it take years to learn python and how to create a bot like the one i want
it will not take years
but we cannot tell you how long it takes because it varies wildly from person to person
i personally took 3 months
when i started i didn't even have a computer, so i took classes once a week
yeah the teacher had these really cool machines with linux mint installed on them
lol
Good Evening everyone! I have come up with a python file to do some status checking on certain game servers. My question is, how can I transform this so it can go into my bot? Or would a webhook be better? I'm not really sure because this is something that checks on an interval basis on isn't through a command. Does anyone have suggestions or recommendations?
for some reason im rate limited on my bot
from discord and it only probably gets a few request every couple hours
are you just running it on your own computer? or on a host?
its hosted
Chat dead fr
what host
I'm making a bot on a host, I get an error and I think it's something with the token, can I send you the code of my bot and you can check what's wrong? My bot doesn't turn on because of that error and I don't know what's wrong.
What is the error?
!paste Show the trackback and the code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the 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.
@fast osprey any idea how to open a modal from a button?
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
So I can put that in the callback for button click?
wsg so i did a dmall command and like it says that people dm are closed while its not (it was working fine like 2 hours ago)
What exactly is dmall
small
dmall is dming everyone in a server
with a command
Did all of the user's consent and ask the bot to get dm'd?
This is against developer policy then. You should use pings within the server
my question wasnt if it was against tos
You should refer to the server rules first, then
What do the rules say?
Pretty bold thing to admit
Let me help you out though:
Rule 5
Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
If what you're asking for help with violates discord's tos (it does), that is against the server rules to ask for help with it or for us to provide help with it. Lucky for you, there is a very straightforward solution that accomplishes the core goal that does not violate TOS
you agreed to the rules by joining and chatting in the server. it is unwise to agree to something without knowing what it is that you are agreeing you.
wym
Is there a confusion about what "rules" means? 
#rules has a list of rules for the server, and this project would run into rule 5. We would not want to assist with a mass DM spam bot
The preferred way for a bot to interact with lots of people in a server would be a ping in channel
In simple terms, asking for help that goes against Discord's rules (Terms of Service) is not allowed. This server follows those rules, so we canβt assist you with anything that would break Discord's TOS.

yo guys my friend is making a discord bot i think through discord.py but his pc is x84 and not 32 or 64 anyone who cpuld like put code in and make bot but like not script it and stuff meaning that my friend will send the code and stuff and you just put it in

May want to check again what x86 is
what even is x84
ima assume you meant x86
its an instruction set for 32 bit processors so not sure what that has to do with a discord bot?
hey, anyone able to help with a discord python bot where I can use the commands globally?
What's the problem/question?
I'm trying to use the new user install feature to use my bot in dms
but cannot figure it out haha
What have you tried!
import discord
from discord.ext import commands
from discord import app_commands
TOKEN = 'tokens' # Replace with your bot token
intents = discord.Intents.default()
intents.message_content = True # Enable message content intent if necessary
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
try:
# Sync global commands
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(f"Failed to sync commands: {e}")
@bot.tree.command(name="test", description="Vouch")
async def test(interaction: discord.Interaction):
await interaction.response.send_message("Vouch")
bot.run(TOKEN)
So firstly, you need to remove your sync from on_ready
Or you're going to lock yourself out of development entirely
Secondly, you don't need user installs to run commands in dms. That works just fine for regular global commands, assuming you share a guild with the bot
you're awesome for responding
but how do I get it working
, could you modify for me?
nwnw! If you do want user installs specifically, you'll need to add the context for it. But you probably don't need it in this case
I don't write code for people
what am I missing for this to work properly then?
because the fixes you mentioned aren't what should be preventing me from being able to use it in dms
am I missing something in dev portal?
Well, this first step should be pretty straightforward
well this shouldn't prevent it from being used in dms, no?
This will allow you to actually fix the problem
If you do not do this, you will not be able to make any changes in the very immediate term
so after removing sync, what's the next action I should take?
Are you in a shared guild with the bot?
yes
Have you refreshed your client since syncing commands?
yes
Is the command in the guild's integrations tab?
My bad internet went out, Iβm tryna use the bot in DMs
Not in a guild
It works in guilds
Does anyone know how to make a stock bot for my discord
i have a website called sellauth
The api key is different i think, i tried using chatgtb but hes dumb
hi
stock means
i made a economy bot like owo now what should i do next ..
Error fetching bot guilds: 401: Unauthorized
What is the full error, including traceback?
Its a website for setting a prefix but on It i try to get what servers the user has admin perms In and the bots In for It to show up. But nothing shows under the guilds tab and I get that error.
Also ping on reply
I have like 10 files.
* Serving Flask app 'server'
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: 235-583-904
127.0.0.1 - - [01/Aug/2024 08:32:04] "GET /thank?code=J6XtUhVR9PL4Sf2OgSNys5jXcQhY31&guild_id=1244010476569100318&permissions=8 HTTP/1.1" 404 -
127.0.0.1 - - [01/Aug/2024 08:32:23] "GET /thank?code=J6XtUhVR9PL4Sf2OgSNys5jXcQhY31&guild_id=1244010476569100318&permissions=8 HTTP/1.1" 404 -
127.0.0.1 - - [01/Aug/2024 08:32:34] "GET / HTTP/1.1" 200 -
Error fetching bot guilds: 401: Unauthorized
127.0.0.1 - - [01/Aug/2024 08:32:38] "GET /dashboard HTTP/1.1" 200 -```
Your first step is to get the full error, including the traceback
that Is the full error
yum
I cant find any other error anywhere.
Because you're throwing it away
"Error fetching guilds" is not something python, discord, or flask would put out. That is you
This typically comes from people try/excepting blanket Exceptions, printing the exception itself and throwing away all of the useful bits. In general you really should not be writing error handling like this
choose a Discord API wrapper (like Discord.py or pycord), get an API that can interface with whatever stock system you use, integrate it using your own capabilities
Can anybody explain me how to create a custom status for my discord bot? Without the Playing, Watchting etc. Just a text
im following a tutorial at the moment and it said to go to terminal and type pip install discord or pip install discord.py yet it doesnt recognize pip as anything
have you installed the latest version of python?
yes i have
oooo tysmmm
or better than installing
git clone https://github.com/python/cpython.git --branch main
./configure
make install
yeah because it's easier running 1000000 tests than pressing a download button
outdated
https://discordpy.readthedocs.io/en/stable/api.html#discord.CustomActivity
|| @wanton current || this should work
This is the activity without "Playing", "Watching" or "Streaming"
Thanks
that's assuming you're using discord.py btw, otherwise you'll need proper docs for nextcord or pycord
Any idea why this code:
async def get_upvote_count():
"""
Function to get the upvote count of the bot from Top.gg.
"""
url = f"https://top.gg/api/bots/{BOT_ID}"
headers = {"Authorization": TOPGG_TOKEN}
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, headers=headers)
response.raise_for_status()
bot_data = response.json()
monthly_points = bot_data.get('monthlyPoints', 0)
total_points = bot_data.get('points', 0)
return monthly_points, total_points
except httpx.HTTPError as e:
print(f"HTTP error occurred: {e}")
except Exception as e:
print(f"An error occurred: {e}")
return 0,0
@bot.tree.command(name="vote", description="Upvote the bot on Top.gg!")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def vote(interaction: discord.Interaction):
monthly_votes = await get_upvote_count()
total_votes = await get_upvote_count()
embed = discord.Embed(
title="Vote:",
description="Go upvote PlaceHolder on **Top.gg**!\nHelp us grow the bot!",
color=discord.Color.blurple(),
)
embed.set_thumbnail(url='https://cdn.top.gg/icons/7b707bf868adef7730776f171a2dc709.jpeg')
embed.add_field(name="Monthly votes:", value=f"`{monthly_votes}`", inline=True)
embed.add_field(name="Total votes:", value=f"`{total_votes}`", inline=True)
view = discord.ui.View()
view.add_item(discord.ui.Button(label="Go vote!", url={URL}, emoji=':placeholder:', style=discord.ButtonStyle.link))
view.add_item(discord.ui.Button(label="Bot page", url={URL}, emoji=':topgg:', style=discord.ButtonStyle.link))
await interaction.response.send_message(embed=embed, view=view)```
Gives a 404 error? ("unknown interaction")
It worked a few hours ago, but Idk why now it doesn't.
π€
You're taking more than 3 seconds to respond
how to create command slash discord.py and run with host bot-hosting.net ?
my errol
pls help me
Did you read the warnings
Yes but I don't know how to fix it
I can run it on replit but not with bot-hosting.net? Why?
Both of those are not good places to run bots
why are discord.py buttons supposed to be like this
async def btn(self, interaction: discord.Interaction, button: discord.ui.Button):
instead of
async def btn(self, button: discord.ui.Button, interaction: discord.Interaction):
Context menu can have how many parameters?
context menu in which?
commands or..
On a message like a report command with 2-3 more parameters
Is it possible to give multiple parameters to context menu?
Like we do for slash?
What do u mean?
I am talking about context menu
!d discord.app_commands.context_menu @willow sable
@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.
This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.
Examples...
ok i got it
uh, someone help, I am new to discord python stuff and when my bot is on and I execute a slash command code the previous slash command won't show up
plz help a brutha out π
What do you mean by "won't show up"?
hi
someone can help me making an discord bot what getting pysilon samples form Triage and ungrabbs the discord bot token form it
and sends it to the discord server
What exactly does "ungrabbs" mean and what are you doing with a token π€¨
I have no idea what a "grabber" is

Who is getting what bot token, and how
like a bot token the login of the discordbot
That doesn't answer my question. I know what a token is
you know pysilon
What is the exact scenario playing out here, it's entirely unclear what you are trying to do
get the samples from triage and gets the token form the pyinstaller file
What are you trying to do
and sends to a discord server
I'm going to get out ahead of this conversation and inform you that distribution of bot credentials (including tokens) is strictly prohibited by the TOS regardless of how you're getting them unless you are qualified as a service provider of that particular bot
but those are cyber criminals
Okay...? So again, what are you doing?
That doesn't tell me what you're trying to accomplish, you're just throwing buzz words around
Without using any specific library or framework, what is the problem you're trying to solve? Someone else has some bot token, what are you trying to do with your code?
Solstice, what he is referring to is "grabbing". This is referred to as stealing tokens that allow unauthorized users to steal tokens or session cookies to login. This effectively bypasses MFA/2FA. This is a very big thing in Discord actually especially in communities where rare Discord account names may exist, rare badges, etc. Or just trying to mess with someone.
However, it's usually NOT just discord grabbing. They usually grab a lot more information including but limited to:
Saved Passwords, CC Info, Addresses, Cookies, etc.
You can read more here on this gist writeup: https://gist.github.com/SpreeHertz/467dbeb05f261d1b92fe6f8d6d2dcc1e?permalink_comment_id=3976567
What happens when you get token-grabbed on Discord? - token.md
Right, I know what this means. What is very unclear is what they specifically are trying to do, materially
I will agree it's severely unclear what he's trying to achieve but it sounds like he's trying to defeat this malware (PySilon) in an automated fashion by taking malware samples and doing something with them. But I have 0 understanding on how he will do that with a discord bot
The specific bit that concerned me (emphasis added by me):
...ungrabbs the discord bot token form it and sends it to the discord server
Yeah, no that is of concern as well. Tokens shouldn't be sent in a server. Again, I agree that it's a little odd.
I believe that sending a bot token to a discord server automatically invalidates it.
no
the best way to defeat these communities is by reporting them to discord, they take these reports quite seriously
From what I can tell you are right and my statment was wrong. IDK why discord does not do it as they warn you not to send tokens so they know a token has been sent.
May be legitimate cases
. Dev team on a private server or something
is it possible to change the bots banner via command?
await edit(*, username=..., avatar=..., banner=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes\-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes\-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.
Changed in version 2\.0: The edit is no longer in\-place, instead the newly edited client user is returned.
Changed in version 2\.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
how to get datetime like this? like the gray thing around it
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.
This allows for a locale\-independent way of presenting data using Discord specific Markdown...
Hello @alpine summit, this channel is unrelated to hip-hop unfortunately.
Why isnβt the url portion of this working? https://paste.pythondiscord.com/FTCA
My discord antinuke bot not work help me https://paste.pythondiscord.com/ZDBA
do you have an error?
what's the issue?
Make sure to provide tracebacks, errors and any other helpful info
Code working but when !MIB
It's doesn't reply me also bot shows offline
@graceful raven
https://paste.pythondiscord.com/ZZQA nev er seen an error like this. im just trying to add a cog to clean up some of my code
pickle tried to store command context perhaps?
what
Could you send the code for that HelpCommand class please
The issue there is the way you import the datetime module
you:
from datetime import datetime
datetime.utcnow(), datetime.timezone.utc
fix:
from datetime import datetime, timezone
..., timezone # not datetime.timezone
recommended fix:
import datetime
datetime.datetime.utcnow(), datetime.timezone.utc
!d datetime.timezone
class datetime.timezone(offset, name=None)```
The *offset* argument must be specified as a [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object representing the difference between the local time and UTC. It must be strictly between `-timedelta(hours=24)` and `timedelta(hours=24)`, otherwise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised.
The *name* argument is optional. If specified it must be a string that will be used as the value returned by the [`datetime.tzname()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzname) method.
Added in version 3\.2\.
Changed in version 3\.7: The UTC offset is not restricted to a whole number of minutes.
Huh where ? Can I share my code
Yes
Sure
!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.
from datetime import datetime, timedelta
At top ?
And line 42 is the error
Actually I don't know python I made this script using gpt and my knowledge can you tell me
And then using it like datetime.timedelta(...), datetime.datetime.utcnow() and datetime.timezone...
