#discord-bots
1 messages · Page 394 of 1
I looked into the docs, it works like that test_emebd = {"title":"...", "description":"..."}
and then you pass it into this method and it creates an embed with the given informations
Do not use from_dict
yeah I know what this method does, embed has also to_dict method
Doesn’t seem like you know what it does
I think you want to use str.join here for the description
data = {
"Foo" : "Bar",
"Foot" : "Ball",
"HOTEL" : "TRIVAGO"
}
friendly_dict = "\n".join(
f"{key} -> {value}"
for key, value in data.items()
)
print(friendly_dict)
# Foo -> Bar
# Foot -> Ball
# HOTEL -> TRIVAGO
# ^ one print
nonfriendly_dict = " AAA ".join(key+value for key, value in data.items())
print(nonfriendly_dict)
# FooBar AAA FootBall AAA HOTELTRIVAGO
It has been 10 and ahalf years since I seen this two
crazy
Hi
hi
Bye

How to get object, ID or Mention Attribute for Sub Commands on App Commands?
When you walk over commands, it can be a group - if it's a group, then it also have a walk commands method or just the commands attribute
Howdy! I have this role menu being added to a server, the emotes are in a different server the bot is in, is there any way for the reactions being added to be those emotes?
emoji_dict = {
'Party': '',
'Challenge': '',
'Crafting': '',
'Valdos': '',
'Divine': ''
}
I have a dictionary of the ids as I read in an earlier post
for emote, reaction in just_in_case.items():
try:
await message.add_reaction(reaction)
And then just basic reaction adding so im not really sure what else can be done
bots have a limited version of nitro, it allows them to react to messages with emojis from any server they're in
- reaction based flows are pretty outdated, and you'll get severely rate limited on reacting. Consider ui elements for things you want users to interact with
- if you just want to allow users to opt into roles, consider the built-in onboarding options (channels & roles menu)
Its not a big server at all, highest load is just going to be at launch, after that im expecting only a couple a day so i doubt rate limiting is an issue
Plus this looks prettier imo if I can get it to work
as well as the mods of the server don't really know what they're doing so I dont think theyll be able to set up the onboarding thing- They said they didn't even know how to add emotes
I mean it exists and is a standard way for people to ask for roles in any server they go into, and doesn't rely on a bot constantly waiting and processing reactions, but you do you
And how do they later opt out or into other roles?
They can opt in and out at will, it's a separate dialogue that's always available (not just during onboarding)
So I know you advised against it, but how would I tell the bot to look out for reactions on a already existing role menu after it restarts x3
You would use on_raw_reaction_add/on_raw_reaction_remove which don't rely on the internal message cache.
you may also be able to force cache the reaction role message by fetching it but i'm not sure how well that would work/if at all
Will do some playing around! Thanks!
having a weird issue and running into some issues trying to solve it.
moved my bots to a new VM and getting the modules installed but everytime I try to start it i get the error message "module dotenv not found"
i have installed python-dotenv and even rebooted for good measure but it continues to do it.
is python-env not what I need?
maybe you are running the bot in a different environment? the lib is correct
My knowledge on discord.py has weird missing chunks, I downloaded it through command line and am running the bot through there. is that not what you mean?
did you pip install the library the same place you ran the bot?
no just the same VM, the same terminal
Yes same VM/terminal
are you using virtual environments or installing globally
installing globally
ok can you paste the install and run command as well as the error?
it might have a hidden detail
Install (in command line): py -m pip install python-env
run (in command line): poetry run python scnewsbot
im getting a problem here: from discord.ui import Select, View
can you try runjning without poetry? I think thjat makes a seperate env
so i got the dotenv sorted out but running into a different issue, its saying the module audioop isn't found, think that one was deprecated so trying to replace with audioop-lts
which is weird ftr because audioop isn't anywhere in my code
so unsure why its even throwing that error??
weird, its letting me start it from vscode, but not from my .bat file which worked before
wtf lmao
maybe your vscode is running a different version?
how can i type annotate channels?
discord.TextChannel
or whatever type of channel
i meant all types of channel
there was an ABC for those i think
discord.abc.GuildChannel?
class discord.abc.Messageable```
An ABC that details the common operations on a model that can send messages.
The following classes implement this ABC...
how can i make my bot send @ everyone without pinging everyone?
allowed_mentions kwarg
It is used within discord.py
Technically discord.py does not support python 3.13 yet. But as far as I am aware the temporary fix is as easy as installing audioop-lts
I did do that but it throws the same issue, would rolling Python back to an older version be better for the time being?
Your choice. Are you sure you installed it in the right place? IE in the same venv as your bot
What is the best place to sync commands when my bot is a "slash commands only" bot?
"Best" is relative. Really it's entirely your preference given only you should be doing it
Sync prefix command, command line param, sync reaction listener, whatever you want
What's sync reaction listener?
Sync commands when you react to a specific message with a (specific) emoji
You can have this trigger off of literally any event you could perform on discord, or something you could send to the process directly
How can I reset the cooldown of a command from another task/function, as well as reset it for all users? I have a daily "checkin" system set up that I want to reset at midnight utc for all users
making a button persistent makes it so you can click the button even after the bot restarts
however setting timeout=None will make it so the button never times out (if the bot restarts the button won't respond anymore tho)
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
thank you
how can i apply a permissions check for all of the commands inside a cog?
This worked tyty
I tried fetching the message but i wasnt able to figure it out
So the raw reaction worked and just have checks if the message is the expected saved message id
Just use the check decorator above the cog class definition
If i remember correctly that's how you do it
its still there
What type of commands?
has anything changed in making discord commands, beacuse i somehow get an error saying Unknown integration after using a command
last time i started the bot was in february, so i am a bit outdated
I solved the problem by kicking the bot and then inviting it back to the server. Did you try that?
Can i use other server's emoji in my bot's if bot is not added in it?
No
Just like you can't use emojis from a server you haven't joined yourself
I made a discord bot for a server I moderate and I want to make a easy to use panel that I can distribute among the other mods to control the bot have yall got any tips on how I can use the ui to make the bot function
how can i add multiple embeds when responding?
embeds kwarg
you can only set that once?
?
oh yeah i forgot there are two embeds and embed
You just can't use both, it's either one or the other
do i combine the embeds with a list? i dont get what does Sequence mean
Where did you get that Sequence from?
Docs are pretty clear
the function signature
in my ide it says Sequence
It's a sort of list
Sequence means something iterable technically
Like a list or tuple
Hello
hi
how to send embeds with multiple pages? anybody an idea?
good, thanks and u?
Same
Im sorry idk
uhh hello i know that this is the wrong channel to ask in but i dont know why "is there a channel to learn how to code python"
well ye there might be
were?
Im sorry I can't find any
But there's app easycoder
U can use it
and i can help too
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
Hey thanks
If you are using pycord you can use ext.pages Im not sure if there are other libraires with a feature like this. But there is not built in API way to do so. So you either have to do it yourself or use a library tool/extension
https://gist.github.com/InterStella0/454cc51e05e60e63b81ea2e8490ef140 a tutorial for how to do so but its dependent on this external package/extension also by same creator as discord.py https://github.com/Rapptz/discord-ext-menus
the logic behind it is fairly simple you can implement it yourself as well without any external dependencies
if you are looking for a readymade library here is one of them https://github.com/Defxult/reactionmenu
A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md
A library to create a discord.py 2.0+ paginator (reaction menu/buttons menu). Supports pagination with buttons, reactions, and category selection using selects. - Defxult/reactionmenu
I created 2 new discord bots and the problem is that they work fine for some time but then stop working without giving any error help
one bot was working fine for 5 days and then stopped working
What does "stop working" entail? Do you have any logs? Is the process itself running?
i cant figure out how to add this image thing in the title of an embed, can anyone help?
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent\-style chaining.
Set the icon_url
oh thanks lol
Is there a way in python for bots, to have like a console command be registered, but with it not like having to always wait for input, cuz that would probably cause other issues right?
Id recommend you just send messages to the bot. It's like a strictly better console
how can i implement a config manager for my bot?
Have a database and save the configs for the guild ids
should i use json instead?
You should not use flat files to store things that are changing at run time
Even then json is a shit config format
isnt a database for structured data? i want to save some config that have different structures
Your data most likely still has some structure. Even if some of it is custom, you can store it in a JSON Column
You can have non relational databases, but there's really no reason to here. You are declaring a relation
You have a finite set of settings
but json itself is non-relational?
Not really sure what you're getting at
wdym am i wrong?
You use a database to record things that change at run time. Period.
You may opt for different database engines depending on the nature of your data
but that would kinda defeat the point since you're still using json?
Only a little bit. The main reason you dont use normal json is because of the fact that it is just a file, reading/writing can be slow and error prone. A database is designed for reading and writing. Also I have ~5 "normal" columns and 1 JSONB column for my semi-custom key value pairs.
Having a suboptimal schema is far less of a problem than using flat files
You could in theory shove everything into a giant jsonb column. This would be slow and strip you of data integrity and other benefits of relational data, but at least you'd have atomic read/writes
oh right so the solution is switch to a database and jsonb columns btw i also want to "automically" create a discord command for each of the config's flag so that i can change it on runtime with less writing is this bad or a good practice? is there a better way?
I am personally suggesting you don't just fall back onto jsonb to avoid thinking about your schema. You do you though
ill try to do it, what about this question?
getting this error while adding a role : nextcord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions What Permission needs the bot? It has admin permisssion (Test Bot)
The bot role has to be above the role you want to add, did you check that?
ohh, yes you are right. It was under the role I wanted to add thanks
You can solve some of the data integrity issues by having triggers that validate that your data is of the correct types.
ManageRoles
Quite obvious, it's one of the checkboxes in the dev portal
If it has admin that's not gonna happen
Unless you've done something wrong
Or maybe...
There is a way to get that error when the bot has admin. And the solution was described in the message directly below the question. The check boxes on the dev portal are just the default permissions the bot will have upon invitation, they can be changed and overridden in channels.
Please read the comment from nightmare77. This was the solution. I have also checked this on the discord website.
Not the server for that, go to Fiverr or Upwork
I can do this
This is a server for learning how to do it yourself, not hiring people. We can't and won't put forth the honestly ridiculous amount of effort required to evaluate job postings and follow the applicable laws for doing so
Any way to improve this?
# Check for Non-English characters
elif re.search(r'[^a-zA-Z0-9\s]*$', message.content, re.IGNORECASE):
modlog_message = "Non-English characters"
do it in automod? 
Doesn't .isascii() do the same
or do you only want actual letters
Oh you mean like message.content.isascii():
yeah
I want to allow English Letters (a-z, A-Z), Numbers (0-9) and Special Characters
Then your regex approach is probably better
Is the regex good? py re.search(r'[^a-zA-Z0-9\s]*$', message.content, re.IGNORECASE):
is automically creating commands good?
as in?
wdym
like wym by creating commands automatically
im trying to automically create a command for each of my config flags yk so that i can change it on the runtime without having to write the same command that almost do the samething
Why would you want separate commands instead of just one command with a parameter? That sounds like api sprawl
some of them have different structure as i said before thats why, also seperating them make it feels way more organized
Making the surface area of your api explode to effectively do N versions of the same thing isn't organized
yes thats why i wanted to automate it so
I'm talking about organization for your end users, not you
You should not be expanding the surface area of your application to do the same thing N times with one very minor thing changing
well if i shove it all into one command how would i add stuff like description, custom parameters to each of the config flags then?
It doesn't have to be one, but you should make a meaningful decision about your api. Not generate it
trying to use forms with discord bots, anybody have experience with it? need a form to popup when a button is clicked that the user can fill out. using nextcord api rn
kinda like this
thank ya
!d discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.
Note
Buttons with a URL or an SKU cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because these buttons cannot have a callback associated with them since Discord does not do any processing with them.
emoji kwarg
can someone familiar with nextcord help me?
Ask your Python question, not if you can ask or if there's an expert who can help.
i tried to add autocompletion to my application command(slash command) but it gives an error
traceback https://paste.pythondiscord.com/FZPQ
this is all the code?
yup
and where is autocompleter used
this is an example of autocomplete in nextcord, have a look
A Python wrapper for the Discord API forked from discord.py - nextcord/nextcord
thank you so much
this is what i needed
the docs didnt offer this
hey guys been experimenting with the discord api, added a kick command to my bot: ```py
def kick_user(self):
if self.events["t"] == "MESSAGE_CREATE":
content = str(self.events["d"]["content"]).split(" ")
if content[0].startswith("!kick"):
if len(content) == 2:
self.discord_api.kick_user(content[1])
else:
print("Command use !kick user_id")
There already exists native features to kick people. Having a bot do it only serves to reduce auditability and security
this also checks if someone has a specific perm to kick user from the discord api side
"Remove a member from a guild. Requires KICK_MEMBERS permission. Returns a 204 empty response on success"
can someone explain how to add an async aspect to it? Which libraries should I use so that the code be more efficient ?
holy moly, I know Krypton chill bruv
then why ask if you know?
for god s... please read my comment
You're asking how to add async aspect to something and make it more efficient
Using the raw api like you do it not efficient at all and should use existing wrappers
If you make your own you should have an advanceed knowledge of the language
Knowledge that makes you know that async is built-in in python with asyncio
So maybe, ask your questions clearly and rethink about randomly insulting
First I dont insult you, second I wrote "experimenting" and third, I know async is built in, and last one I dont make any wrappers!
Then you have the answer your question already, what's the point in asking things you already know
can someone explain how to add an async aspect to it?
You apparently know asyncio, so question answered
Which libraries should I use so that the code be more efficient ?
asyncio, you already know
I asked the question because I use a primitive websocket library that doesnt have async to it, and I use requests library which also doesnt have async to it.
No point in a websocket connection async, you only have a single one that runs in background
aiohttp for non blocking http requests and websocket sessions
so aiohttp is for http requests and websocket connections?
read the docs, that's what it says -> https://docs.aiohttp.org
ok I am going to read through it
That doesn't matter. You are a) not adding anything and b) removing security (2FA checks)
nextcords docs are ass
how does discord.py run slash commands
How it works in the background?
- you register a function to run, your command, with its respective name
- discord.py is connected to the gateway and receives events
- once it receives an
INTERACTION_CREATEevent it will get the commands you've created and run the command based on the name received in the event
now how they're internally called, as in what method is called/executed, would need to read the source
yes where does it run the command
yes sir we getting there 😜 ```py
def on_member_join(self):
if self.events["t"] == "GUILD_MEMBER_ADD":
user_id = self.events["d"]["user"]["id"]
role_id_member = xxxxxxxxxx
self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member)
works too now we can add a welcome message in the welcome chat hihi
funny how your methods never have the required arguments to actually do what you want to do
what yall think of that ? ```py
if self.events["t"] == "GUILD_MEMBER_ADD":
user_id = self.events["d"]["user"]["id"]
role_id_member = xxxxxxx
self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member)
self.discord_api.create_message(channel_id=xxxxxxx, payload={"content":f"Welcome {self.events["d"]["user"]["username"]} to the the server. Have fun and enjoy the trip!"})
In need of lots of abstraction
And checking for if self.events["t"] == "GUILD_MEMBER_ADD": at the beginning of a on_member_join function is kinda weird
Should check for the events, parse the data and send that over to the function as argument
I have just worked a little bit with the discord api so I am kinda exploring and let me have fun but thanks for your inputs
Man if you're getting that defensive and pissed when you're the one asking for feedback, just don't ask already
anyone have experience with selfbot development?
!rule tos
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Selfbots are against discord tos and will get yourself banned
its completely for a non-malicious purpose
Doesn't matter
Doesn't matter, selfbots are against tos regardless of what you do
I am not pissed but you can tell me what you mean by parse data send it as an argument etc with examples not just with theory but ok, so i can implement it
alr thanks ig
that is your perspective and your reality, but for me I am not pissed, I have the will to learn and explore new things
this dudes been typing for 5 mins holy hell
wow, and so. Teaching needs his time and finding the right words!
Then ask.
Parse data as in you get the data in the d field based on the event, the fields are listed in the docs.
E.g. the guild member add event returns a member object, which will always have the same fields.
So you can parse that JSON data into a custom member class you'll create. Then you can pass that along to your method.
if self.events["t"] == "GUILD_MEMBER_ADD":
# parse the content of "d"
member: Member = ...
# use that parsed data for your method
self.on_member_join(member)
Then you can use the class directly in your function, e.g.
def on_member_join(member: Member):
print(f"Member {member.user.username} joined")
Thanks Krypton! I will have a look after a break and try to implement it. When I have further questions, I will post them here
Then not sure how your internals work, but self.discord_api.create_message is maybe the wrong naming, something like self.http.create_message is better
And for self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member), adding a role requires the guild id, not sure where you get that one from. Same for self.discord_api.kick_user(content[1])
You can't add a role based on its id to a user based on its id, you need the guild id.
You can't kick a user just based on its user id, you need the guild id.
the testbot is only for my test server so the guild id is stored no worries
Endpoints are PUT /guilds/{guild.id}/members/{user.id}/roles/{role.id} and DELETE /guilds/{guild.id}/members/{user.id}
Right then it makes sense, just make sure the bot is not in other servers if you don't read the guild id from the events you receive
I am not sure with http since it is a module and I dont know if I get an error but I try it
Then go for _http
Can i ask for codes? the code that im looking for is a way to put the output in a channel like a Bot logs
# Modal form input
class FormModal(nextcord.ui.Modal):
def __init__(self):
# Create a text input field for the modal
super().__init__(title="Purchase Form")
self.add_item(nextcord.ui.InputText(label="What are you buying?", placeholder="Units, Items, Gems", required=True))
async def callback(self, interaction: nextcord.Interaction):
# Capture the user input from the modal
user_input = self.children[0].value
await interaction.response.send_message(f"User is buying: {user_input}", ephemeral=True)
tried to make forms like Tickets bot has, completely lost to what im doing as I've never worked for nextcord API before, please help!
heres the goal form
We help you code, we don't code for you and offer you the source later
are you sure you want to install dotenv instead of python-dotenv?
oh, then can you give a source for learning python?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thx
Im having a hard time doing self learning
cuz everything on YouTube is for windows or smth like a computer or laptop
it is absolutely worth the investment to purchase a computer if you want to learn programming
you can probably get one for <$100
in my country 1USD is 60 of our currency
:(
okay then 6,000 of your currency
Theres no results :(
Your first step is going to be stop using YouTube for educational content
Im still 14 yrs Plus im jobless and has school:(
Like yt is the only place that i can learn
rn
It's not
Where else can I learn python?
^
try edx
youtube content, especially in this sphere, is produced by people in their basement who want internet points. It is not quality controlled, it is not updated. It's one dude making shit up 99% of the time
And beginners are not going to be able to tell the difference
yeah man sometimes
hey guys, just updating you. I have made a small approach and implemented a user object into my bot, so we can extract the username and id
what casn I improve ```py
if events["t"] == "GUILD_MEMBER_ADD":
user_obj = User(events)
self.client.on_user_join(user_obj)
the naming. members are members and users are users. Idk what you call users if you're calling members users but it's best to stick to the originally provided name to avoid confusion
yeah thats what I thought and changed it no worries
nice
did anything changed with the .url attribute?
None has never had a .url
Thx!
wait now i have this
hello! got a question about something, using discord.py, not sure if their was a new update that came through or something because lines 7 and 9 are not working anymore so I was wondering how I can get it fixed
line number 9 is where i got the major problem from the looks
That's a syntax error
You can't leave functions empty like that in python
And what are those imports doing in teardown
idk why it is coming up in teardown
and i am not sure how to fix it me and my friend do this together and he is the smarter one and isn't responding to my dm's...
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yea i am confused tbh
# invalid:
def my_func():
# valid:
# Invalid if the above function isn't removed or given content
def my_func():
... # placeholder
let me see if i can find the file my friend sent me
you define a func in python like that: ```py
def func(param):
..........instructions
def means define
https://paste.pythondiscord.com/DAHQ that is what my friend sent me (and the bot deleted it and needed me to put it into that link)
if it doesn't work let me know
what means that parrot reaction?!
Repeating what has been said already
bruv chill holy
I'm chil? Lol
when you get so pissed from that then I am sry but I wanted to help
Lol that's definitely from some tutorials or chatgpt
Idt your friend knows what they're doing either
Consider following the official examples and working from there: https://github.com/Rapptz/discord.py/tree/master/examples
Like see basic_bot.py
yea we're both new to this
sooo that kinda doesn't help
or just connect to the websocket and make http requests
Chatgpt isn't going to help with anything. Consider learning python and starting with something basic like a rps game
chatgpt is not always good. It makes mistakes too like a human does.
yea ima go ask him idk wtf is going on anymore tbh
what project are you guys aiming for?
multiple propose bot for fun but i might use it to become a real dev
nice
yea i got 2 projects going one that is javascript and the discord.py one
yeah sounds cool
doing 2 code langagues is hard but i need to figure out which one i am going to use mainly
so you are familiar with javascript?
ok, dont know about that
ok googled it, it is a botmaker
yea and they call it "the best" but they got major issues
like rn with shards going offline
had all my bots go offline like all day because of it
bro just used botghost to get his active dev badge...
yea and it was the easiest thing to use according to my friend
which
on 2nd though is harder
work for it 😭

nah if i do i get over worked
thats the point
Chat gbt better lol
Huh
@hushed galleon, I was wondering if I could talk to you in dms? I have something to ask you. But no channel would fit here, its something personal to you.
where can i find that part of the error in the code
How can I reset the cooldown of a command from another task/function, as well as reset it for all users? I have a daily "checkin" system set up that I want to reset at midnight utc for all users
guys, I need some advice. I struggle a lot with the member object and dont know how to start , so far I have this but I dont know if that is kinda messy to do: ```py
class Member:
def __init__(self, event):
self.member = event["d"]["user"]
@property
def username(self):
return self.member["username"]
@property
def id(self):
return self.member["id"]
are you making your own api wrapper
no, I am just experimenting with it. The websocket connection is good. Receiving events, but how to flow the data is the struggle point
!cban 1114384953329860710 NSFW gif
:incoming_envelope: :ok_hand: applied ban to @sharp crane permanently.
wow.
does anyone know how to check if the bot has permissions to timeout a member?
Hey guys,
How do i install the audioop module?
If on python 3.12 or lower, then it is builtin, if you are on python 3.13 or higher install the audioop-lts package
thanks anon, i just downgraded
okay thx :)
where is discord.py stored and where do i find it in a docker enviroment
it is stored where all of your other pip packages are stored
yeah i don't really know where that is
if you're not using a venv, you can check by doing:
import sys
print(sys.path)
and then it's in the site-packages for the python version you're using
yeah i know
but there is no site packages
there is no python3.13
the folders dont exist
/usr/local/lib/python3.13
And 3.13 isn't supported by python api wrappers, just hikari iirc, either way
hey krypton
So far the solution is to just install audioop-lts have you come across more incompatibilities with 3.13?
I think command flags broke as well, but tbh most people should be using slash commands anyways.
there has been other issues
y'all would approve ? ```py
def on_member_leave(self, member: Member):
self.http.create_message(channel_id=xxxxxx,
payload={
"content": f"User {member.username} has left us. Till next time buddy ):"})
Looking good, payload could be updated a bit though
Build the payload in the create_message function. Make the rest normal arguments of the function, e.g.
self.http.create_message("Hello world", channel_id=...)
mhh ok, yeah, you right, just write a string not a dict, ok gotchu
self.http.create_message(xxxx, f"Member {member.username} has left us. Till next time buddy :(")
it works sounds great

Uhh Theres an error on line 215, but my code only consists of 89 lines
Wth
!source
It is probably line 215 in a different file within your discord library. If you post the traceback we can probably help
the traceback is long, is that ok?
Does discord py support user-install?
Global commands, for instance they can use it in discord DMs not just servers
its a app not a bot
User-Install-Application
yes i use it for Warn command
No, not sending in DMs active in DMs
dm command just trolling friends tho
or warning them
No you can use it for other things globally
No not the bot sending them a message
nope
bruh
damn thx
Yes
If it is super long you can put it in !paste
!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.
Can you send a example
I dont know discord.py I just know that they support it. You could join there support server and ask or what for someone else.
so i just !paste <code> ???
No you paste your code on the website, click save, then copy the link here
oh ok
https://paste.pythondiscord.com/JKFQ
@stark ingot
Whats wrong?
The error says what is wrong, the Member object has no attribute user
Did you mean their username, their mention, their id?
i mean i used this {member.user}
not {member.mention}
Yeah, but what is your goal with {member.user}? A member is a user so all the information you need is already in the member object.
Command-Logs a Channel/event that Sends the User that Uses A type of command and who uses it
So it sounds like you probably want to use the mention parameter instead. {member.mention} just use this like you said above
oh ok
Bruh i just rechecked the code I am just missing an f string:/
I wasted So much time
Thx for the help anyway
why is my mention having two @s?
Because the role is called @ everyone, not just everyone
There is no folder named that
Who has a link for documentation or crash course for a Discord bot
Please i really need it and want it
just make http requests
http?
joking
you can read the docs
it is on the developer portal
or youtube yeah
but i dont know abou that
you think youtube would help you @toxic notch
Theres no helpful info for A discord bot it only shows "How to make a Discord bot without coding" Type of shit
You have experience with python?
I need some help with Modal. I can't seem to find examples using cogs, it's always a single file execution and not a cog added to the bot. I want to make form basically, and I found it randomly, if anyone has some ressource to share :)
https://github.com/AlexFlipnote/discord_bot.py This is pretty helpful
🍺 A simple discord bot that helps you getting started within discord.py - AlexFlipnote/discord_bot.py
Idk how to use github
i admit that im new
You can just download the repo
I also was new to it you just gotta learn how it works
im on mobile
You don't code on a PC?
Nah Id suffer coding in mobile
4GB of Ram
32 GB of Memory
Mediatek cpu
how can i make an alt detection for my bot?
I used to code on mobile only the other day
And I learned Python on my phone
Also made a discord bot
how can I reset the cooldown of a command for all users?
Reload the cog/bot
is there a more "efficient" way? not complaining about the answer, thanks for it, but i want to know if there's a better way that doesnt involve restarting an entire section of the bot
hey yall
what is that for a reaction?
he gave you a link to the docs
why question mark?
@dense falcon
linking the docs without saying a thing isnt exactly helping (especially when ive already read them over like 10 times 😭)
cmd = bot.get_command("cmd")
cmd.cooldown.reset_cooldown()
wait does running it without context reset for everyone?
willi is prodigy in python and discord.py so he is right
hollup just a moment
oh
yeah you may need a context
try this: https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Cooldown.reset
# so just
command.cooldown.reset()
the other one was linked to a specific command, not the cooldown itself
how can i check if a interaction response is already deferred?
A hands-on guide to Discord.py
!d discord.InteractionResponded
exception discord.InteractionResponded(interaction)```
Exception that’s raised when sending another interaction response using [`InteractionResponse`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse) when one has already been done before.
An interaction can only respond once.
New in version 2\.0\.
So I am making a battle bot that has an inventory system linked to google sheets. However when I run the battle command, it raises an "'int' object is not callable error." I don't know what that means. Here is the code.
# player1 has heavier attack
if player1.attack == 'Melee' and player2.attack == 'Magic':
player1.inv[0].damage(player2)
await ctx.send(f'{player1.id}\'s {player1.inv[0].name} overruled {player2.id}\'s {player2.inv[2].name}. {player2.id}\'s health: {player2.hp}')
elif player1.attack == 'Ranged' and player2.attack == 'Melee':
player1.inv[1].damage(player2)
await ctx.send(f'{player1.id}\'s {player1.inv[1].name} overruled {player2.id}\'s {player2.inv[0].name}. {player2.id}\'s health: {player2.hp}')
elif player1.attack == 'Magic' and player2.attack == 'Ranged':
player1.inv[2].damage(player2)
await ctx.send(f'{player1.id}\'s {player1.inv[2].name} overruled {player2.id}\'s {player2.inv[1].name}. {player2.id}\'s health: {player2.hp}')
# player2 has heavier attack
elif player1.attack == 'Magic' and player2.attack == 'Melee':
player2.inv[0].damage(player1)
await ctx.send(f'{player2.id}\'s {player2.inv[0].name} overruled {player1.id}\'s {player1.inv[2].name}. {player1.id}\'s health: {player1.hp}')
elif player1.attack == 'Melee' and player2.attack == 'Ranged':
player2.inv[1].damage(player1)
await ctx.send(f'{player2.id}\'s {player2.inv[1].name} overruled {player1.id}\'s {player1.inv[0].name}. {player1.id}\'s health: {player1.hp}')
elif player1.attack == 'Ranged' and player2.attack == 'Magic':
player2.inv[2].damage(player1)
await ctx.send(f'{player2.id}\'s {player2.inv[2].name} overruled {player1.id}\'s {player1.inv[1].name}. {player1.id}\'s health: {player1.hp}')
Ik spaghetti code
I am a bit of a noob
you really need to be careful, this looks like it'll get out of hand really quickly and will be daunting to edit in the future
either way, please send the traceback
Okay thanks for the advice, sending traceback...
the error is probably because player.inv[...].damage is the name of a variable, make sure your variables and methods don't share the same name
(without a traceback I can't be sure)
I was right
Omg yeah thank you so much
I'll be more careful next time
gl on your bot
I found what im trying to find sry for wasting ur time
Getting a KeyError: 0 when trying to get the support server invite. The YML file is to store all the configuration data needed.
print important_data, it's a dict not a list
pls use match case 
Is there a variable for a users custom status value? Im trying to make my bot send a message in a channel when a user puts a certain phrase in their custom status, it sends the message, but it also resends it when the user goes online an offline
Custom status:
how would print help?
it would help you see what important_data actually refers to and then you'd figure out how to get the data you want
ah kk
This is my firt real attempt at making a discord bot and im so happy with the results i just have to share it
what this custom roster does is, it tracks the roles in the server and updates the roster when someone new is added to a role
it also allows you to click on the name of a user in the list and it will redirect you to their user profile
i blocked out any association to the server its from just so that im not promoting it
Nice!!
2 things:
- I think you should exclude the
-from the masked link so it is not blue - Keep in mind message, description, and field size limits. If you get to many peoples with roles you might have to split this up into multiple messages/embeds
yeye you can already see me struggling with the embed fields, i made it work like columns to just extend into the fields below it aka 2 would extend to 5
Oh yeah. Dont mean to burst your bubble but that may not show how you want it on smaller screens like on a phone
oh yeah i already know
my plan is to add a button on the bottom of the roster to transition it from pc version to mobile
Smart, that is a cool idea/workaround. Keep up the good work!
thank you very much
how do i make my bot set a permission to this middle slash
when editing the overwrite, instead of True/False make it None
oh thanks
Hello everyone I wanna know if it’s possible to create a bot that auto exchange money, like from PayPal to crypto (ltc/btc…) ty for ur answers, the exchange will also take fees while going the transactions like the person send 10€ PayPal and want ltc , she will receive 10€ -6% fees
First question you have to ask is, how do i magically convert 1 currency into a different one. Then you'll find out you cannot do this yourself, especially in bulk...
So first you need to find a service that converts for you, and look for an api. Which nowadays doesn't really exist anymore i think, due to KYC (Know Your Customer).
i have a task loop set up to restart the cog daily, however it seems to miss the timing it needs. It should be executing at 6am UTC. here's the relevant code - I know the function works since I've ran it from a command.
from datetime import datetime, timezone, time
resettime = time(hour=6, minute=0, second=0)
@tasks.loop(time=resettime)
async def reset_daily(self):
cog = Profiles(self.bot)
await self.bot.remove_cog("Profiles")
await self.bot.add_cog(cog)
print("Successfully reset Daily Streetpass and Checkin")
Without looking at the docs, i would assume the way you have it setup now is that it just runs it every 6 hours
There is no mention of a timezone anywhere so if thats not the case, i would assume it is maybe defaulting to a different timezone?
it should be defaulting to utc according to docs, and using time in tasks.loop says it should be executing that time of day
i will check again though
Yeah i just found this example in the docs:
import datetime
from discord.ext import commands, tasks
utc = datetime.timezone.utc
# If no tzinfo is given then UTC is assumed.
time = datetime.time(hour=8, minute=30, tzinfo=utc)
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.my_task.start()
def cog_unload(self):
self.my_task.cancel()
@tasks.loop(time=time)
async def my_task(self):
print("My task is running!")```
my baaaad i didnt know you had to start a task
ive never seen examples in docs tho, where did you find it?
ahh ty
somehow my whole bot refuses to do anything except print to output now so i have some debugging to do before i implement this 😭
Nope I’m not taking about converting a cryptocurrency into a cryptocurrency but a PayPal amount into a crypto currency Wich I will put the stock
For expl :
I have 1500$ in my PayPal account and I will put 1000$ in the Ltc balance of the bot then if someone want to exchange 100$ for expl he send money in the PayPal account and then he paste his ltc addy after that he receive the money in Ltc with fees 6% for expl
It's hard when you don't ask anything in the first place
Unrelated to this channel & server
Use google or something like that to search for English courses or school
Pretty sure this is illegal -_-
And not a python discord bot question.
Hello Fadi, your on a python discord server. I mean you can learn english by praticing to write here in english and ask your python related questions here. If you want to learn english, you can use software like Babbel or go to an english school in your area.
hi guys i want to make a discord bot for cod 1 servers status
but i dont know that much
so if someone is really know that much python
that he can help mee
so plz
no one active
ahhh
why illegal ? Exchanging pp to crypto was never illegal
You are essentially operating as an exchange, And exhcnages for one need to be licensed and registered. Secondly they need to adhere to AML and KYC laws...
All depends on your country but i'd be carefull with what you are doing.
Also pay attention to taxes and stuff
apart from the above
this also violates paypal's terms of service
Which is the least of your concerns at this point but yeah haha
😂 lol
Love the simplicity of your site btw 🙂
woah thanks
To be honest, it seem like you do not have a strong understanding of python and/or discord bots.
Aside from the other legal and TOS concerns you should not be handling money unless you know 100% what you are doing. One wrong line of code and a malicious actor could steal all the money from the accounts
How to setup AutoResponder. Message create
love ya
Discord pybots
Will be easier to help if you describe the behavior you want, and also what you've tried and where you're stuck
Floor the xp so it looks nicer :)
ok ty
by that you mean keep it at a solid number?
You can keep the decimal if you want, just when you're printing it, i think its math.floor(value)
Itll just look nicer
how to make a reminder command or a command which pings me daily perodically
thats a very vague question
Basically just what i need to learn/do
To make that kind of stuff
Look into discord.py's documentation.
They also have examples that should gte you half way there regarding tasks:
https://discordpy.readthedocs.io/en/v2.4.0/ext/tasks/
Thank you so much
Hi All, I am working on a project where I have to access servicenow API using the login credentials , extract the data from Api and load to a Postgres DB. Could you please provide me any available references/resources and thoughts for this project. Thank you
This is the discord bots channel, you would have better luck asking somewhere more relevant such as making your own help post #❓|how-to-get-help
For a guild role using an id it would be this yeah?
specific_role = discord.utils.get(guild.roles, id=1158834836161691810)
Yeah, or just guild.get_role(1158834836161691810) if you're going to be using an id anyway.
Okidoki
You could use some APIs for the rank
Also round to 2 decimal places only
Or round the number to be a whole number
i might just make it no deimals
Yea round up
These are the api’s iib3xu has
@zenith cipher
@shell adder dm him for it
It’s unlimited usage and free
Quick question
What would be the best way to perform threshold cleanup?
Let's say a user sets a certain amount of actions in a period of 30 seconds (example)
That would mean after 30 seconds i would need to run a task, is there any other way for a better efficiency?
considering tasks can increase memory usage by a lot?
How do i get a category by name?
You don't really need api for this
Can i request for an Discord Index like every code for A discord bot? (ex. At bot.command or bot.event)
This is not a code sharing platform
We help you with issues with your code
Bruh i thought i can get useful documentaries here
I believe you're looking for National Geographic
How do i cluster my bot?
Error in class won't propagate to command to stop execution
I have a command to send Modals back to back from a single View object:
# Create an instance of the DropdownMenu view for the oc names
template_selector = MyView(labels=template_names, values=template_names, bot=self.bot)
await ctx.send(content='**Select the template to use**', view=template_selector)
await template_selector.wait() # continues after stop() or timeout```
I use button to confirm entries after the modal is filled to send the next one. But for some reason the code keeps being executed after the `await template_selector.wait() # continues after stop() or timeout` even if an error is detected in the last modal.
```python
try:
# Create an instance of the DropdownMenu view for the oc names
template_selector = MyView(labels=template_names, values=template_names, bot=self.bot)
await ctx.send(content='**Select the template to use**', view=template_selector)
await template_selector.wait() # continues after stop() or timeout
print(template_selector.value)
# COMMAND STOPS HERE IF THERE WAS AN ERROR IN THE MODAL INPUTS
# Create instance of the ColorPicker DropdownMenu view
view = ColorPicker(bot=self.bot)
await ctx.send(view=view)
await view.wait()
colour = view.colour
await ctx.send(f'You have picked {colour} for your OC!')
# Prepare the picture to be stored in the database
oc_picture = await picture.read()
except Exception as e:
# Handle any exception, prevent further execution
await ctx.send(f"Command stopped due to error: {e}")
return # Stop further execution if there's an error
One of the modal (the last one has the following function):
async def on_submit(self, interaction: Interaction):
# Collect and store user input for each field
for item in self.children:
self.user_inputs[item.label] = item.value
# Process the input for Ability Scores and Modifiers
try:
ability_scores = self.user_inputs.get("Ability Scores")
ability_modifiers = self.user_inputs.get("Ability Modifiers")
scores = list(map(int, ability_scores.split(',')))
modifiers = list(map(int, ability_modifiers.split(',')))
# Process the valid data
ability_data = {
"strength": scores[0], "dexterity": scores[1], "constitution": scores[2],
"intelligence": scores[3], "wisdom": scores[4], "charisma": scores[5],
"str_mod": modifiers[0], "dex_mod": modifiers[1], "con_mod": modifiers[2],
"int_mod": modifiers[3], "wis_mod": modifiers[4], "cha_mod": modifiers[5],
}
await interaction.response.send_message(f'Characters information successfully saved!\n{ability_data}',
ephemeral=True)
self.stop() # Stop the modal to allow the next modal to be sent
return ability_data
except ValueError as e:
await interaction.response.send_message(
f"Error: `{e}`\n**Please enter exactly 6 values for both scores and modifiers as shown in the placeholder.**",
ephemeral=True
)
raise Exception("Invalid input in ability scores or modifiers.") # Raise exception to stop command
The exception works just fine, but it doesn't propagate to the command and won't stop it
[ERROR ] discord.ui.modal: Ignoring exception in modal
why does it ignote the exception
To not break your whole bot
How to i get list of users added into channel ovetwrites?
The error tells you in English where to go and how to fix it
I'm currently working on creating a simple Discord user bot in Python and need some help to get started. This is a new concept for me, and I'm not sure how to approach it. Specifically, I want to know:
- How to register commands for the bot.
- What functions are needed to make the bot work.
- The basic structure or workflow for building the bot.
If someone could share a short example code or point me toward useful resources, it would be a huge help! I've searched through various sites and servers but haven't found anything clear or specific yet.
Thank you in advance for your support! 😊
Have you already selected a library?
not yet. i don't have any idea about that type of bot
making a bot and making an embed for an announcement. I want the bot to ping everyone outside of the embed. Whats the code for that
i cant find it anywhere
I recommend this one, you can follow the installation guide and it also has instructions for basic functions:
https://guide.pycord.dev/introduction
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
Everyone?
i want to make a user bot. i have some idea to make a guild bot with prefix command and slash command. but i can't find a perfect documention for the user bot
Read the guide I sent you, it also contains the creation of commands
yeah
i got it tho. I just made it send a another one first
If you are using py-cord they have a user app example here: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_users.py
It is pretty barebones, showing only what makes a command a user app instead of a guild app. The other examples on the github repo for app-commands still work the same way so you can reference them as well. The only difference is the contexts and integration_types
content=“” embed = “”
Ty ty
https://paste.pythondiscord.com/QHAA
Can someone help me with this?
I am using the Pastebin library with discord.py
The pastebin library had its latest release 8 years ago. So it is probably intended for use with an older version of python. I would look to see if you can find any more up to date libraries to use
You may have to create your own api wrapper as it does not look like there are many options. Otherwise you could try to fix the current one
Try hikari
I personally use py-cord. I generally do not recommend switching libraries as there is generally little benefit
using whatever you're already using is the best thing you can do unless you have a good reason to switch
trying to make bot reply to a ping of myself
I tried this but didnt work
anyone know what i gotta put in the parenthesis to make it reply to ping
I also tried <@&USERID>
Maybe logging that content will help you debug what's happening here
it logs fine
nothing comes up
They mean that for issues like this you can often solve them by printing what you are comparing. For example print the message content so that you can see what you are getting when you ping yourself
If your looking for a mention in the message rather than use message.content why dont you look at the message.mentions for your tag ?
How to make user install commands
It's different in every library
import discord, os
from discord.ext import commands
from discord import app_commands
bot = commands.Bot(intents=discord.Intents.all(), command_prefix="!")
@bot.event
async def on_ready():
await bot.tree.sync()
print("Bot is ready")
@app_commands.command(name="test")
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.allowed_installs(guilds=True, users=True)
async def my_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am installed in users by default!')
Why dpy has provided fields then?
I don't know exactly, I don't use discord.py
What you use?
py-cord
Can you share small example?
Like this
I need urgent
But it's different from discord.py, if you use Discord.py it won't work
I will migrate
I only need 2 command in bot i don't have to worry about other library
You can follow the example of the repository:
https://github.com/Pycord-Development/pycord/blob/master/examples%2Fapp_commands%2Fslash_users.py
Remember to uninstall discord.py first
Module discord has no attribute Bot
I don't have time for experiments
I'm even ready to switch to node if that works
Did you uninstall Discord.py?
Obviously not
Are you using a virtual environment?
Yes i use conda
Create another virtual environment and then install there
Install what
py-cord?
Okay and?
You can do it if it's easier for you.
And then follow the example I sent you.
I just want what works
I don't care language or library
Do you know JS and Python?
It says no module named discord
I knew python but haven't practiced it in a year
Show me your pip list
If you don't know JS well you may have problems if you switch to node
I cannot use this for some reason
I'm using replit it keeps installing discord py
@scarlet tiger you here?
i'm not sure what you mean... like there is cogs with that feature you could load and unload that your @app_commands.allowed_installs(guilds=True, users=True) might represent their use for a standard user, not something i have tried tho, but cogs do.
I just want to use commands in dm
Slash commands
you can send dm's with the bot you can also use commands in the dm wiith the bot but i don't know of any way you can use it like a built-in in any DM. the lines you have as decorators can be set to allow the use of the command in different scopes like a list of guilds or users for example and if you just want it in a dl say false to the guild.
in the guild
in the DM
Okay worked
But is it possible to remove that reply reference thing from user commands and show it as normal message?
no
I thought follow-ups worked on user apps too? Just limited to 5
you still gotta reply
Ah, yeah i forgot that had the little "reply" line above it too
Is it possible to
send stuff using webhook
then get stuff again from that webhook?
I hope that possible
because i could use discord for accounts then
else ill use mysql
You should not use discord as a database IMO if that's what you're asking
How can I do that on Visual Studio Code when I want to create a command for my bot, it will be in a new file and not everything in one, I know its c something but idk how to use it pls help DM me
What library are you using?
Wait so I just replace message.content with message.mention and it should do what it showed you?
yes and then you can get the data you want from each of the objects
Ok ok
i dont understand what im supposed to fix
message.mention doesn't exist
das what he told me to do
mention.add_reaction neither btw
message.mentions is not the same as message.mention
preferably on mentionc cuz idk commands yet
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
It returns user objects, not strings
nothing showed up in console eitha
Convert that list of user objects to a list of ID
There are other methods as well, but probably an easy one to do
i literally just started and still on youtube videos
so idk how to put that into a code

your_id = 123456789
if your_id in [user.id for user in message.mentions]:
print("Mentioned")
W
Consider learning python before though, discord.py is not really for beginners it's more for advanced people
I already learnt how while back
so i know basics of python
I know the names of everything I just dont know how to put those together to make smth work
Basics are not enough
where do i learn
if "@Taco" in message.content:
Won't work, not how mentions work
tried that
Lots of websites (e.g. codecademy) or books
Roughly the required knowledge before making a bot
Prerequisites
Some prerequisites for writing a Discord bot in Python.
Required:
- Primitive data types
- Operators
- Control flow
- Function definitions
- String formatting
- Variables, namespace and scope
- Importing
- Classes, objects, attributes and methods
- OOP
- Data structures
- Exception handling
- Console usage, interpreters and environments
- Decorators
Useful to know:
- Databases
asynciobasics- What is "blocking?"
- Logging
- Reading documentation properly
as said it's an object and you need to "extract" the values you need from it.. i would try a dir on it to find out what it has or read the docs for that item....
I made a discord announcement without knowing shit
:D
Mentions is not the property you want to use
channelId=["1126839090587897866", "1126839177976221786", "1126839219738923070", "1117543378872193074", "1117543448698953859", "1117543493724807250", "1117543598494318693", "1120701899939794974", "1120702042801975438", "1124856806976524328", "1123761521512693760", "1123750319508160573", "1123750583183089684", "1125084175163207750", "1125084175163207750", "1125085306215997572", "1125085976386089020", "1125085976386089020", "1124270543437303859", "1117472177298608199", "1129367300609429534"]
if str(message.channel.id) in channelId and "@everyone" in message.content:
channel = client.get_channel(message.channel.id)
channels = client.get_channel(1126244432719646801)
embeds=discord.Embed(title="Your message has been deleted", description=f"**Reason:** \n Attempted everyone ping \n \n **Channel:** \n {message.channel.mention} \n \n **Remember to read** [#1117542377880555631](/guild/267624335836053506/channel/1117542377880555631/)", color=discord.Color.purple())
embed=discord.Embed(title="This action is against server rules", description="Your message has been deleted", color=discord.Color.purple())
await message.reply(content=f"{message.author.mention}", embed=embed, delete_after=15)
await message.delete()
await channels.send(content=f"{message.author.mention}", embed=embeds)```
this is the most complex thing ive done
use message instead, and add the reaction to message
Content is not any better, you're checking for the ID either way. So who cares
Also, to check for a specific user when this one is tagged, you should use ID's
You can just use automod for that :^)
ik but whats the fun in that
Exactly what was done, thanks
auto mod cant do specific channels tho

Channel IDs are int btw
No need to store them as string and then do str(message.channel.id)
Just do message.channel.id in channel_ids and store the IDs as normal int
It's just unnecessary convertion
You could convert them three times in various other data types and it would still work, it's just pointless and unnecessary
how long do u think it would take to get the knowledge to make a good bot
without u guys help
balls
!e
a = 1
b = 2
print(str(a) == str(b))
Pretty much what you're doing
:white_check_mark: Your 3.12 eval job has completed with return code 0.
False
yeah, was searching for such a screenshot
Depends the time and effort people put in
hour a day
Less than a few weeks are more than enough if you put in like 3-5 hours a day
yesss
heyy can we not use that kind of language here please thankss
Not sure if you figured it out yet, but pings in messages are formatted like <@USERID>, so pinging you would be @ornate sapphire
(And channels are almost the same being <#ChannelID> )
I was talking about myself tho
Yeah I tried but still didn't respond to the ping
I know, but we just want to avoid it in general please
this should be:
if '@ornate sapphire' in message.content:
bla bla bla
Do you have to look at every channel like all the time???
There's a lot of channels... u need to get paid fr
I feel like all mods for big servers should get paid lol
Alr lemme try that. Thanks
Fr tho. Who tf volunteers for that
I mean it's understandable if it's a small server, but idk about big servers
@unkempt canyon makes our life a lot easier
fair
Ohhhh i djd get a dm
It notifies you too?
Send me the codes. I need a copy this
Fr fr
idk why im surprised the python discord bot is written in python
also, is it on_ready or on_connect that you should avoid using
i remember one of them isnt great to use for triggering one time when the bot comes online
Anyways, look at my highly over complicated way of reading a token that i made just because i wanted it to be expandable
I made it like a year ago and never got around to making a better solution
(First image is the bot's main.py and the second image is readconfig.py)
You shouldn't use any event really for anything you want to happen once
I'm trying to use app command and it works 3/10 times rest of the time it shows this Error
@fast osprey
happens when you take 3+ seconds to respond
How do i fix?
make your code faster 
It's just a simple embed command
unless it's your network
How can i make it faster
anything in your code can slow it down if it's blocking, not just that command
Is there no other solution?
It's a single command code literally 40 lines 😭
I have it hosted
How do i handle this and make it work?
@client.tree.command()
async def confirmation(interaction: discord.Interaction, amount: float, user: discord.User) -> None:
await interaction.response.send_message('I am installed in users by default!', ephemeral=True)
How can this be slow? Rest are only follow ups
The issue is definitely network and i cannot fix that on hosting so
^
how have you determined? What's your ping?
I have no idea
import discord, os, asyncio
from discord.ext import commands
from discord import app_commands
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
await self.tree.sync()
intents = discord.Intents.default()
client = MyClient(intents=intents)
@client.event
async def on_ready():
print("Bot is ready")
@client.tree.command()
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.allowed_installs(guilds=True, users=True)
async def confirmation(interaction: discord.Interaction, amount: float, user: discord.User) -> None:
await interaction.response.send_message('I am installed in users by default!', ephemeral=True)
embed = discord.Embed(title="Transaction Detected", color=0x5865F2)
embed.add_field(name="Required Confirmations", value="`1`", inline=True)
embed.add_field(name="Amount Received", value=f"`${amount}`", inline=True)
await interaction.followup.send(embed=embed)
client.run()
That's all
can you print/log out client.latency?
Lemme do this
Returned this
not network then
I don't understand what is wrong

You could compare the interaction's creation time to the current time before you try to respond
What's the best way to reload a bot for all servers (cogs & slash commands & py-cord)
as of now i tried await bot.sync_commands() it doesnt work
I have all 3 downloaded/imported in my code and it says i dont have them? why??
hey still having the issue?
did you sort your problem in the end ? you know if you want to listen with no command for your tag you can just use a listener that will just check every message but it you want it in a command you can do that also, i put above the listener with no command.
Did not notice you wanted a reaction add if it is seen maybe this is more what your after ?
You also dont have to explicitly check for the id's either if you dont want that huge list.....
if user.name.lower() == "yak":
await ctx.message.add_reaction("👻")
ah
Hey guys, is there a public bot on Discord which keeps an eye on Github repositories and posts updates in a server channel when something changes? I been trying to find one but all of the ones I could find are DIY bots. 🫤
yes
Yes...?
idk if its bot or integration
but u can put webhook in github repo
that works only if its ur repo or u have admin on one
This should work, can you try adding the commands you changed to the commands kwarg, if that still does not work set the force kwarg to true with the commands that were changed.
Overall, I generally think the best solution is to just restart your bot and not deal with cog loading and unloading when using slash commands
You might need to restart the discord client
I found that after adding/modifying commands that they wont show until i switch accounts back or restart discord
Oh yes, don't know why I did not mention that ^
Try this first
Note that you can use ctrl+r to reload
Oh damn thats nice to know
It still won't answer tk a ping of myself
event-listener or command, which you using ??
None
no
well what do you want to use ?
On message
!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.
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.mentions:
for user in message.mentions:
await message.channel.send(f"User: {user.name} | ID: {user.id} | Mention: {user.mention} | Name: {user.display_name}")
if user.name.lower() == "the_tag_here":
await message.add_reaction('👻')
await bot.process_commands(message)
can anybody help me with this error
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
you need to install module 'settings'
pip install python-settings
I think
Most likely just trying to import a local file
What the actual fuck is this env wrapper
https://pypi.org/project/python-settings/
pydantic_settings 👍
<@&831776746206265384> against discord tos + server rules
please help me with this problem in my code on_member_remove function is not executing or working.
Also show your intents
no
And in the developer portal?
yea they enabled
this is weird then
this is my code
import discord
general = 1304417440587059234
from discord.ext import commands
class Client(discord.Client):
async def on_ready(self):
print("ready")
async def on_message(self,message):
print('recieved msg')
print('recieved message')
if message.content == '!hello':
await message.channel.send('Hi, do you need me? just use !help for commmand help')
async def on_member_join(self,member):
print("Somebody joined")
channel = await client.fetch_channel(channel_id)
await channel.send(f"Hello {member}")
async def on_member_remove(self,member):
print("member removed")
channel = await client.get_channel(channel_id)
await channel.send(f"Unfortunately, {member} has left..., He will be punished for that crime.")
channel_id = 1304417440587059231
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
client = Client(command_prefix = '!',intents=intents)
do you run the client anywhere...?
yea i cropped it out for obvious reasons
What gets printed
nvm
everything works except
import logging
import discord
from discord.ext import commands
from discord import app_commands
#CHANNELS AND THEIR IDS+=======================================
general = 1304417440587059234
class Client(discord.Client):
async def on_ready(self):
print("ready")
async def on_message(self,message):
print('recieved msg')
print('recieved message')
if message.content == '!hello':
await message.channel.send('Hi, do you need me? just use !help for commmand help')
async def on_member_join(self,member):
print('member joined')
await member.send('Welcome to DBP!, Enjoy Your Visit. ')
await client.get_channel(general).send(f"Welcome to DBP {member}!, Enjoy Your visit")
async def on_member_remove(self,member):
print('member removed')
await client.get_channel(general).send(f"Unfortunately, {member} has left..., He will be punished for that crime.")
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
client = Client(command_prefix = '!',intents=intents)
GUILD_ID = 1304417440587059231
@client.tree.command(name='hello',description='Say hello',guild=GUILD_ID)
async def hello(interaction: discord.Interaction):
await interaction.response.send_message('Hello there!')
client.run('MY KEY
')
@client.tree.command(name='hello',description='Say hello',guild=GUILD_ID)
^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'tree'
this aint working
and if i change client to bot then the client events wont run
Clients don't have a tree
You have to make one yourself, or use ext.commands.Bot instead of Client
can you show me how to add / commands in a bot because these are not really well documented and alot of videos are outdated
import logging
import discord
from discord.ext import commands
from discord import app_commands
import discord.ext
import discord.ext.commands
#CHANNELS AND THEIR IDS+=======================================
general = 1304417440587059234
class Client(discord.Client):
async def on_ready(self):
print("ready")
async def on_message(self,message):
print('recieved msg')
print('recieved message')
if message.content == '!hello':
await message.channel.send('Hi, do you need me? just use !help for commmand help')
async def on_member_join(self,member):
print('member joined')
await member.send('Welcome to DBP!, Enjoy Your Visit. ')
await client.get_channel(general).send(f"Welcome to DBP {member}!, Enjoy Your visit")
async def on_member_remove(self,member):
print('member removed')
await client.get_channel(general).send(f"Unfortunately, {member} has left..., He will be punished for that crime.")
class Bot(discord.ext.commands.Bot):
async def on_message(self, message):
print('working')
async def hello(interaction: discord.Interaction):
await interaction.response.send_message('Hello there!')
async def add_command(self,command):
return super().add_command(command)
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
client = Client(command_prefix = '!',intents=intents)
CommandClass = Bot(command_prefix='!',intents=intents)
GUILD_ID = 1304417440587059231
i have no idea where to go from here
Yeah you shouldn't be referring to videos at all IMO. It's just randos making stuff up. You should stick to the official docs of the library you're using
yea videos didnt help at all and i ve read the whole documentation of discord py 10 times atleaxt now but for each event or class there are like 2 lines and no real description or example
thats why i am here
https://about.abstractumbra.dev/dpy has good examples and explanations for discord.py
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
oh thanks
Also read the examples in the repo, not just the docs
guys, how would you add mongodb to a discord bot. I thought, make a seperate file called database.py and connect to the db and import the file when needed to insert, delete etc. But is that efficient or correct? Pls educate me
mongo tends to be a pretty crap db choice anyways, and it's highly unlikely that your data is actually nonrelational
what file you put the logic in is pretty much your choice and won't impact things functionally. The logic itself is what matters
I use mongodb since it is easy to learn I mean just "dictionaries" so, no database diagramm (hahah) and stuff like that. But you approve my approach for it, I mean It can be also implemented with other databases?
You shouldn't angle your design based on what's easiest
If your data is relational (it very likely is), you should use a relational database
like mysql you mean with the database language sql?
of course, mongo db is No SQL database, so it can be helpful for storing dictionary. but there are some dis-advantages in it. if you can, you can use PostgreSQL database. you can save all type of SQL, NoSQL data in it
Ok sounds good. Would you approve my approach for adding into a discord bot?
The question of that stuff living in another file isn't particularly interesting or relevant. You could have very poor code in a very neat file, or very good and optimized code in a giant shared file
of course, but if you don't need store too many data, firebase is the best optional, I think
ok, sounds good. What if other files need to ex insert data into that db? How would you solve this?
good old firebase. I actually built a chat app with it in python
ok
do you have experience with relational db?
of course, I often used RDBMS recently
sql databases have many advantages so it is widely used
you want to store chat history in sql db?
no, but when I hear relational, than I think of a diagramm where I put every table in a relation. Is it that complicated?
@ebon lynx
not at all. it is not so hard work
sounds great
excalidraw is ok
Usually you don’t have too many nested relations so you don’t even need something to make diagrams or whatever on
designing diagrams are for full projects in enterprise level
I forgot to ask this last time, is there any convention or good practice in using one over the other?
between what options?
doesn't work
most likely a file you're trying to import
but apparently you don't seem to know that, which makes it probably not your code either 
Code:
async def roblox(ctx, username):
await ctx.send(f'Fetching information for {username}...')
user_info = get_roblox_user_info(username)
if user_info:
await ctx.send(f"User ID: {user_info['id']}\nUsername: {user_info['name']}\nDisplay Name: {user_info['displayName']}\nDescription: {user_info['description']}")
else:
await ctx.send('User not found.')```
Error:
```line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: tuple indices must be integers or slices, not str```
**Can someone help me**
user_info is a tuple, but you're trying to index it as if it were a list
Can you show the get_roblox_user_info function?
Hello! Someone has been telling me that security bot premium, in case of a channel deletion, they would restore ALL messages from that channel, which would mean storing all messages and sending them throught webhook, which technically it's bad practice to do that, since you would overload your database, and would make it a lot slower for indexing, and they responded with "im sure they don't do it that way", Which is impossible to do it in another way, am i right?
Considering you cannot pull off the messages on_channel_delete event once the channel gets deleted, if they said maybe 20-30-50 messages, it would of had been more normal, but all? It's impossible without storing them to a database, right?
Let's also considering the fact that it would require them to store a user object to send the message throught the webhook looking like the user, and also ratelimits for sending messages...
Tell me if im mistaken, thank you.
If you're storing users' messages in any fashion, you're subject to the data privacy to sanyways
if there is anyone who wants to build a discord bot with me and is kinda new to python dm me
PYTHON IS THE BEST
What you described is not unique and also very against TOS
i was joking
i dont do such dumb shit
Good joke 
Hello i have created a group command:
@ecoadmin_group.command(name="removecoin", description="Remove coins from a user's balance.")
@commands.has_permissions(administrator=True)
async def removecoin(self, interaction: discord.Interaction, user: discord.User, amount: int):
if amount <= 0:
await interaction.response.send_message("You must remove a positive amount of coins.", ephemeral=True)
return
self.economy.update_balance(user.id, -amount)
await interaction.response.send_message(f"Removed **{amount}** coins from {user.mention}'s balance.", ephemeral=True)
Despite of adding '@commands.has_permissions(administrator=True)'
Still the non admin users have access to the restricted commands. Please help 🙂
this is a slash command, stuff from discord.ext.commands won't work on it
also, you need to put the check on the group parent, not the children
guys i made a bot to remind me when anime epi comes out using web scraping but i wanted to add a funtion to it so that when my leptop or code stops working it should save what anime i asked it to remind and load them up when i run the code again but it doesn't seem to work anybody if has an idea pls help
!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.
web scraping == against 99.9% of website's tos