#discord-bots
1 messages · Page 923 of 1
S.M.H. stop cringing 
just help Daxles, I'm going on a stroll 😔
dax
did u load the extension??
Yeah
show
from the main file?
yes
I mean other cogs work
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
But that won't be the problem right
complex
Please don't use ableist language.
saad
Just make sure that ur cog is loaded 🤷🏾
yes
Filters called us
ok.
Our bot is a snitch 🙂
:>
Facts
someone or the other is probably just lurking here every time 
..
ur cogs are not loaded
listen try putting other command in the help cog and test if that command is working or not
Ok
huh?
I will just leave 
I beg you to elaborate what these periods mean
Wait is ur help command outside the folder("cogs folder") orr ur help command in another folder
i beg u to stop
What have I done?
nothing thats why
Cool
^
@junior verge
salad
just that
Nah its in
working?
uh lemme try
Who tf is salad
^
I see a Saad in the chat
import discord
from discord.ext import commands
import os
@bot.event
async def on_ready():
print("Logged in as", bot.user.name)
@bot.event
async def on_member_join(member):
try:
channel = bot.get_channel(WELCOME_CHANNEL_ID)
try:
embed = discord.Embed(colour=discord.Colour.green())
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.add_field(name="Welcome" ,value=f"**Hey,{member.mention}! Welcome to {member.guild.name}\nI hope you enjoy your stay here!\nThanks for joining**", inline=False)
embed.set_thumbnail(url=member.guild.icon_url)
await channel.send(embed=embed)
except Exception as e:
raise e
except Exception as e:
raise e
bot.run(BOT_TOKEN)```
lol
what is the error?
Using a class?
bruh?
Traceback (most recent call last):
File "main.py", line 7, in <module>
@bot.event
NameError: name 'bot' is not defined
Wtf
toatally not copy paste
What theme is that?
Can i see ur files/folders? Something like dis

define bot/client
What the hell is this?
^^^
mm
it will say that that command is not as well
ur cog is not loaded!!!!!!!!
confirm
Yep alright
confirmed by sparky
But thats weird since my other cogs are loaded
Maybe I shouldn’t have left discord bots lmao wtf is this chat
Yup that works fine
It's #discord-bots :)
its prob with loading
ironically
Ig?
I didn’t know that
im sure
and how to fix that
Lint being nice to humans
I found the issue
Now you know 
You’ve…never loaded cogs before?
i use bot.load_extension() 🤓
Command inside init
Fucking
Thats what loading cogs means
Wait so what is the problem?
!d disnake.ext.commands.Bot.load_extensions is cool btw
indents
load_extensions(path)```
Loads all extensions in a directory.
New in version 2.4.
i use that only
But that's disnake only ig
omg
:D
im disnake
Same
Yeah
Unindent the command
simple and easy
Eh, I would still prefer manually looping
who cares
Recursion supreme
🤌true
If you loop manually you can exclude certain files you don't want loaded
Can't do that with load_extensions unless you edit src
you can
How?
Um you are supposed to provide string not the module
pc laging like hell
😫
!d disnake.ext.commands.Bot.load_extensions
load_extensions(path)```
Loads all extensions in a directory.
New in version 2.4.
You just provide a path to the folder
What is the command that tells how to read traceback
Can't you just help me instead
It's pretty clear
Just read the traceback properly and you will be able to easily help yourself
Yeah but how to fix it
it would be a lot easier if you send your code first of all
Read this https://realpython.com/python-traceback/
!traceback
🤨
i just have a list of extension strings and iterate through and load them
no organization of the project
...........
you can use Intents.all()
Gotta disagree
.
^
dont know about that
why do you keep putting .? What's it supposed to do?
6 same statements with only one argument varying
supposed to mean*
Sure
!paste
why would you even wanna exclude certain files
you can loop through the cwd (since there are no nested folders/subdirectories) to load the cogs
does anyone here know how to end the code in pycharm? because the bot is still up even though i terminated it already
end the code?
i did
CTRL+C should cause the program to stop
alright im gonna try that
i just delete the terminal in vsc
yeah same
so delwarn isn't in the list
delwarn shouldn't be there that is correct
so why are you trying to remove it?
So it won't show up ugh
I usually organise the bot project like this
src | cogs
cog1.py
cog2.py
ext
utils.py
bot.py
res
nice_image.png
nice_image2.png
main.py
.env | encrypted token
i DID it slightly diff
it doesn't work for me
Yeah ofc it might differ from dev to dev but almost everyone stores cogs in a separated folder
so basically, does the bot never go offline after you destroy the terminal?
print the list first
Pycharm?
it might take a little bit for the bot to go offline, from my experience
look at what the list returns, before doing list.remove
yes
mhm
Yeah I removed the remove delwarn thing
When will prefixes be cancelled
Cause in pycharm ctrl+c doesn't work for me as well but I only tried aiohttp servers there
rip
There's stop button however that works
^
its still online even though i stopped it
Online you mean even responding to commands?
btw if you just CLOSE the terminal (Ctrl+`), the bot won't go offline
so it works?
My command works now but just my serverstats command shows up
yes its still responding
you have to actually destroy the terminal or stop the bot instance
And what IDE are you using?
no idea what you mean
Like the command should show all the cogs and the name/description, but it only shows this
um pycharm
Okay and how do you stop your bot?
can you print the list cogs = [c for c in self.client.cogs.keys()]
just print it don't do anything else
just print(cogs)
yes
the square button ?
Ok that should be a right way to stop it
if not idk
Check the run tab if there's anything
its still responding to events/commands
even though i stopped it
it doesn't print it wut
error?
None
I remember several other users faced this issue but I don't remember the solution to it
what is the command code you ran?
If I would be using pycharm I would probably figure out why it happens but in this case I don't know how to help you sorry
None just want to print it
huh?
is it a bad thing? like the bot running even though i stopped it already
It is abnormal
also instead of async def help(self, ctx, cog="1"): why not async def help(self, ctx, cog : int = 1):
Normally it would stay online for approximately 1-2 mins but not respond to commands and then just go offline
Depends
Yeah okay, now the command just shows the delwarn lol
Why you overriding builitin help lmao
builtin is shit
Check pins for the proper way of implementing help command or do
@commands.command(name="help")
async def _help(...):
...```
And yeah better check pins
okay
your better off subclassing it so you don't have to write all the shit
Well why does it now just show my warn lol
!d discord.ext.commands.MinimalHelpCommand
class discord.ext.commands.MinimalHelpCommand(*args, **kwargs)```
An implementation of a help command with minimal output.
This inherits from [`HelpCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HelpCommand "discord.ext.commands.HelpCommand").
?
is there any efficient way for an help cmd with slash cmds?
I don't think there's a class for slash help command yet
No besides creating own class
Or doing a simple command
hmm ok thanks
but why
cant you use
minimalhelpcommand and the other preset ones
in a slash command?
can we?
It uses context so most likely it sends to channel
i tried commands.HelpCommand it didnt work
Because it's not interaction based
Probably need to do some research in low-level stuff of the lib
On the message to command processing stage
commands.MinimalHelpCommand? i dont know can slash commands use codeblocks?
You can create it in a class and use it in a slash command?
Slash commands are based on interactions, and the help command subclasses are based on simple message sending
cant you reroute it
Caught in different events
whats more useful of having your whole bot basically invisible to anyone except for the people who use it
You can but pretty sure you'd need to edit library files
i dont get everyone making every command they have into a slash command
most people using dpy 2.0.0 have it git installed
Ik
But I think you can't reroute help command processing without editing the library files which means creating own fork
You can't spell it wrong, you only get a few options, so it won't return any errors.
but like.. spell it right? that works
you arent going to have 3 year old children using your discord bot im positive if they could add it they know how to type right
It's nice to see all commands pop up, instead of using help command for viewing the commands and then spell it carefully
And try to remember which argument is where
Also easier for dev, doesn't have to make error messages (for giving feedback, what went wrong etc)
['Whois', 'Ping', 'Role', 'Warn', 'Avatar', 'Mention', 'ball', 'Moderation', 'Meme', 'EmojiInfo', 'Help', 'Serverstats']
Which are all my cogs but just 1 shows up on my help command
Now it just shows whois
It just gives a random cog
'\n'.join(cogs)
Show me the code
So only 1 cog appears into neededCog list?
Yeah
Probably this part messes it up : x = i + (int(cog) - 1) * 4
i made a class for the help command with select menus.. how do i call that in a slash command with disnake?
disnake is weird
im a dpy guy but i could probably help you
idk how forks changed things
@tidal hawk
this is my first time using the lib
so im having some confusions
this is the exact same as dpys examples
ik its a fork but like.. they just switched like 2 things around and called it theirs
no?
yes
How many cogs do you want to display in one page
where
where did they say its theirs
nvm thats nextcord
4
nextcord is trying to make it seem like they arent a fork by changing EVERYTHING
v3
no
You found solution?
Nope
yes
hello, can anybody pls help me my cog aint loading in heroku
What makes you say that?
errors?, Probably issues with path if it works normally but not in heroku
yeah it works properly
No
but not working in heroku
it needed 7 contributors to fix one tutorial file
Huh?
Do you got a requirements.txt?
You can't define a module by seeing just a single commit... I'm not being biased here, but you should also look at the other features like faster releases bruv
That doesn't make any sense, just look the number of contributors in discord.py examples folder.
2?
Do you got a requirements.txt
im talking about the file itself
could you link me the file
i dont even have a problem mate
And may I know why you are looking at only that thing? There are other plus points of the module too, to look at
Pretty sure mine should work though just don't see the problem
it was what got brought up
thats 2/5
and if you read the commits
-
disnake's example has been updated to support the v10 which is yet to be implemented in discord.py?
-
They formatted code with black in one of the commits. & linted the file
v10???
Yea
breh
It's released
v10 is released?
Yea...
thats why you need to read the commits, discord API has different versions as well.
Bruh
they dont work well with version numbers

discord.py 1.7.3 is on v8
april 30th danny is pushing an update so its compatable with v10
Hahaha
for cog in neededCogs:
commandList = ""
for command in self.client.get_cog(cog).walk_commands():
if command.hidden:
continue
elif command.parent != None:
continue
Don't mind the weird indent (copy)
But you reset the string
Every iteration
thats what im saying, there will be more commits in dpy's repo too with the update in the package
https://discord.com/developers/docs/resources/channel#embed-object-embed-limits
Does this mean that each embed (in the list of embeds that a msg can send) has a per embed limit of 6k chars or that the total char limit of each embed in the list combined must not exceed 6k chars
Additionally, the combined sum of characters in all
title,description,field.name,field.value,footer.text, andauthor.namefields across all embeds attached to a message must not exceed 6000 characters. Violating any of these constraints will result in a Bad Request response.
yeah but i dont rlly get how disnake can already get 2 api versions ahead with the last update to the api push (so its compatable) being in like 2019. meaning it went from v8 to v10 in less than 2 years. idk what discord is doig with versions but its quite weird
v9 was realeased on April 28, 2021, danny started working on 2.0 and it was to be included in it
but since it never got realeased, there;s the gap
v10 has been released recently
but then v10 drifted and crashed and blew up in a firery mess into the repo?
think it's got do do with all the new interaction stuff, that's gotta require lots of restrucrting on their backend. wouldn't be surprised if we were on v11 API by the time the new permissions system is added
right. interactions are now a HUUUUGE part of discords bot scene in general
the development was stopped due to app commands and message intents shit
and that doesnt really affect the old api
ah
think d.py 2.0 is already compatible with v10 API according to this https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6#v10-of-the-api, unless i misunderstood your msg
discord/http.py lines 274 to 275
class Route:
BASE: ClassVar[str] = 'https://discord.com/api/v10'```
Hey how to know if a user entered the server? Like I wanna display a welcome message so if user enters how to know that he/she entered?
i second that^
it is, but features are limited to forks, like you cant have slash commands in cogs.
on_member_join and on_member_remove
both are events
Aha thanks a lot ill checkout now!!
gl
You can
everyone in the dpy server says you cant
They added support recently
do you mean dpy 2.0 can't have slash commands in cogs? bc that's not true, you most defiantly can and in fact my bot is doing that (albeit in a way too overcomplicated way to meet my usecase)
in the dpy server when anyone asked everyone said you couldnt
yep new feature
how new is it
when did you ask that?
pre march break
they added support a weekish ago i think, maybe a bit longer
Not sure but having the control is nice
But how would I exclude certain files with load_extensions
Pretty sure you can't
How would i filter audit logs entries that were moderation actions, like bans, kicks, mutes, messages etc with disnake.AuditLogActionCategory
!d disnake.AuditLogActionCategory
class disnake.AuditLogActionCategory```
Represents the category that the [`AuditLogAction`](https://docs.disnake.dev/en/latest/api.html#disnake.AuditLogAction "disnake.AuditLogAction") belongs to.
This can be retrieved via [`AuditLogEntry.category`](https://docs.disnake.dev/en/latest/api.html#disnake.AuditLogEntry.category "disnake.AuditLogEntry.category").
It's maintained by another dude I think
No
Yes
Right
yeah
danny lost interest? idk
yeah this is how I'm declaring my cog class (inheriting both Group and Cog isn't needed for everyone I'm just doing it so I don't need to declare a group later on, as I need that option later on) https://github.com/SnowyJaguar1034/Zupie/blob/fd409e115d56a4d34ec989c46b80be04686cf033/bot/cogs/users.py#L15 and then you add the cog the same way you used to https://github.com/SnowyJaguar1034/Zupie/blob/fd409e115d56a4d34ec989c46b80be04686cf033/bot/cogs/users.py#L112-L113
bot/cogs/users.py line 15
class User_Cog(app_commands.Group, commands.Cog, name="user", description="Shows all user related commands, legacy and slash"):```
`bot/cogs/users.py` lines 112 to 113
```py
async def setup(bot):
await bot.add_cog(User_Cog(bot), guild=Object(id=default_guild))```
He didn’t like how discord was forcing slash commands
Yeah
ohhh i see
He was infuriated due to discord employees of not answering his question (they have also insulted him)
i got insulted by a discord employee once
then discord support ghosted me
Oh
what is one man gonna do about a multi million dollar company
That's what they said?
To you?
no they told me my responses were unprofessional and immature and just stopped responding
anyone has discord custom help command dm me or paste it here please.
i just asked why their staff were acting like toddlers
SUIII
n o
shush
We won't spoonfeed you code
That's not what this server is for
i have it already
but i wanna add my own help command idk how
thats what google is for if you are a degenerate
class MyHelpCommand(commands.HelpCommand):
async def command_callback(self, ctx, *,command=None):
if command:
await ctx.send(f"This is the help page for the command {command} ")
else:
await ctx.send("This is the front page for the bots help command")
bot.help_command = MyHelpCommand()```
just tell me where i should paste my own help
WELCOME_CHANNEL_ID = 955795195268567130
import discord
from discord.ext import commands
import os
from keep_alive import keep_alive
client = discord.Client()
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = '!', intents=intents)
@client.event
async def on_ready():
print("Logged in")
@client.event
async def on_member_join(member):
try:
channel = client.get_channel(WELCOME_CHANNEL_ID)
try:
embed = discord.Embed(colour=discord.Colour.green())
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.add_field(name="Welcome" ,value=f"**Hey,{member.mention}! Welcome to {member.guild.name}\nI hope you enjoy your stay here!\nThanks for joining**", inline=False)
embed.set_thumbnail(url=member.guild.icon_url)
await channel.send(embed=embed)
except Exception as e:
raise e
except Exception as e:
raise e
keep_alive()
client.run(os.getenv('BOT_TOKEN'))
``` how can i fix this it worked but when someone joined it didn't say anythiing
```py
for easier formatting and color
oh ok
you can just use channel = client.get_channel(955795195268567130)
okay
and you can remove the field and have name and value as title and description
iin the main embed
also the member "icon" is actually member.avatar_url < 2.0.0 but if you are using 2.0.0 its member.display_avatar.url
and guild isnt used
its just member.name
also i see you're using replit. pro tip: dont.
member.avatar.url still works if you want the users default global avatar, display_avatar is the guild specific one
First variable should be string i belive
if it isnt guild specific it gets the normal one
its just easier
I have a json file like this:
{
"ID": [int1, int2]
}
I have a guild_id. How can I check if guild_id matches one of the int in the json file?
nope. channel ids are always intergers
Well...
hi
hi
Can someone help me with this?
Okay.
guild_id is a int right ?
Yep.
Compare guild_id as an interger and check if that guild_id is in the ID of the json file.
for _id in YourJsonObj["ID"]
if _id == guild_id:
# do stuff if they are the same
else:
# do stuff if they are not the same
you can open the json file in r, as f (can be anything) then read it like myfile = json.read(f) and use .get to get the ID. and then use myfile.get("ID") and you now have the guild id, and the other id inside of it. you can do whatever with them now
make sure to replace YourJsonObj with your json obj
cant you also use [0] and [1] to get the first and the second?
Hey I wanted to know that
If a user ran a command for e.g: ,knock-knock
And any user sent “who’s there?” The bot would respond with anything like “me” and much more
If this is possible please explain
thats not what he asked for
using random
The thing is, the json file can be bigger than that.
yello
That’s not what I meant
As for now, only 2 ints, but later on, I want to add more ints as well.
one sec
Ah, got this.
So I should use for.
I mean if user1 used a command ,knock-knock
And the bot sends any message I want and then
Let’s take the other user as user2 or anything
If he/she responds with “who’s there” then the bot should reply with “me” or anything like that
And after that the command should timeout
@bot.event
async def on_message(msg):
if msg.content == "who there?"
msg.channel.send("me")
Not this lol
or you can search for it in google
if guild ID in YourJsonObj["ID" ] :```
like how to wait for msg
you can
oh. wait for user response, if you want anyone specific just make the user ping a member with member: discord.Member obj. you can pretty much use bot.wait_for to get a user message and reply with whatever you feel like.
you can also use what @naive pumice did
the user doesnt have to be the author. it can be anybody and you can check if the response fits the citeria. in this case "knock knock" and execute code. then if else just rerun the wait_for.
@slate swan look at this https://stackoverflow.com/questions/54723139/discord-py-how-to-wait-for-author-message-using-wait-for
just wait for any message if it fits knock knock (in samandra's case) do stuff
or who's there
yeah i know
its inside of a command
Hmmm
if msg.content == "who's there": wait for msg....
Did this and else got triggered.
Above:
with open ("./test.json") as f:
data = json.load(f)
id = data['ID']
hows this guide i'm working on? https://sifte.github.io/discord.py-guide/
json file:
{
"ID": [38938246574374913, 859030372783751168]
}
data.get(id[0]) gets the first
data.get(id[1]) gets the second
Bro, the json can be maximized later.
based on your json file having an array
And actually, I use another lib.
And the method to get guild id is ctx.guild_id.
Not discord.py.
Oh ic
ohh
why convert it to an int if its already an int
Just to make sure.
Try printing the ID before entering the condition...
ah
You mean the guild id first?
Which lib?
Because this is an interactions based bot.
And the structure for slash commands that dpy uses is pretty suck, in my opinion.
doesnt mean you need to use a whole different lib
Yeah, I know, but just my preference.
The interactions.py used to act as an extension for handling slash commands/components for dpy before the development got ceased. After that, the dev team decided to separate from an extension to a standalone lib.
ah
Yep.
🙃
@crimson nova whats the issue? 😔
why do people subclass bot? I want to write something about it and need some information on it
all I know is that it is done to add methods but are there any other applications or reasons?
Basically to do other actions along with or instead of already made ones in superclass and for better code readability
Expand functionality
ive been typehinting with my bot subclass for better ide autocompletion
to look cool? 
For example you could subclass it to implement a database inside
member_name, member_discriminator = member.split('#')
ValueError: not enough values to unpack (expected 2, got 1)```
```py
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)````
how can I make it so you can use their ids as well
This is how I subclassed one of my bots, as you can see there are super init, checks addition and extension loading on initialization, override of start to create the database if it doesn't exist, override of close method to close the database connection as well, some database tools and events overwrites
https://github.com/BobuxBot/BobuxAdmin/blob/master/tools/bot.py
im gonna scare the shit out of people with this
Nah not really the discord token generation is epic
its just id and timestamp,, then hash
get user creation, get raw number. base 64.
getid. base 64
line 59, in get_prefix return prefixes[str(message.guild.id)] AttributeError: 'NoneType' object has no attribute 'id'
i get this error when im sending things to my bot - i have made a modmail system and this sends
Hey @proud rain!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
someone who can help?
^^
Lucas Unban 
U can't I am afraid unless user inputs it
from discord.ext.commands import AutoShardedBot ImportError: cannot import name 'AutoShardedBot' from 'discord.ext.commands' (C:\Users\ramzi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\__init__.py) PS C:\Users\ramzi>
why even would you split it
and that for loops only saves the last user in the list
line 59, in get_prefix return prefixes[str(message.guild.id)] AttributeError: 'NoneType' object has no attribute 'id'
i get this error when im sending things to my bot - i have made a modmail system and this sends
Modmail
https://paste.pythondiscord.com/kojucuniwi
Can someone pls help??
so what to change?
do some error handling
perhaps only return message.guild.id's stuff if message.guild exists
are you guys having a good day
else like !
but im not the best to englsih can you help what to change
i am just wondering what's this error
from discord.ext.commands import AutoShardedBot ImportError: cannot import name 'AutoShardedBot' from 'discord.ext.commands' (C:\Users\ramzi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\__init__.py) PS C:\Users\ramzi>
check if message.guild:
learn english > learn python
and only then return that value
return prefixes[str(message.guild.id)]
else:
return "!" ```
this makes the prefix ! in DMS
(ig)
don't scream at me if it don't work
why even add that else
not required when you are using return
i think you gone me wrong, because when i type in dm to the bot this error comes, and i want to get rid of it
in get_prefix return prefixes[str(message.guild.id)] AttributeError: 'NoneType' object has no attribute 'id'
and you could write it as
return prefixes[str(message.guild.id)] if message.guild else return "!"
this should work maybe
exactly what I was talking about
dunno about the order, in that it does this
if it does the if first, then yeah
then I aswell learned something today

!d discord.ext.commands.AutoShardedBot
class discord.ext.commands.AutoShardedBot(command_prefix, help_command=<default-help-command>, description=None, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") except that it is inherited from [`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient "discord.AutoShardedClient") instead.
hm
@fresh iron what's your dpy version
well, you do not have servers inside dms so thats why the message.guild returns None and has no attribute id, so thats what meh was talking about that if message.guild will check if the message was sent in a server or not, if it was then it would be to return the guild's desired prefix, and using a return statement, the function stops the execution of the function any further, and if message.guild returns None, the function should return a ! prefix
😩
how to check that again pip discord version?
its because i made a mod mail system and when i try it out and sends a message to the bot, the error comes
god
import discord
print(discord.__version__)```
!d discord.version
discord.__version__```
A string representation of the version. e.g. `'1.0.0rc1'`. This is based off of [**PEP 440**](https://www.python.org/dev/peps/pep-0440).
but i dont know which line or where i should paste it -_-
replace the line that throws the error
line 59, in get_prefix
return prefixes[str(message.guild.id)]
AttributeError: 'NoneType' object has no attribute 'id'
with this
okay
Message was sent in DMs
if message.guild: #checks if the message was sent in a server or not
return prefixes[str(message.guild.id)]
return "!" #returns a default prefix if the message was sent in dms
And in DMs there's no guild ofc lol
I gave you a paragraph of explanation and you arent even gonna try
https://github.com/kyb3r/modmail swear this is the best modmail u can get, u probably should use it instead
noob
It's more interesting to create own code isn't it
You can make your own too
yes 
not if you don't even know english
Understandable
sorry, im sorry if i wasted your time
I've done that and it's better because you have control over everything
yes
Oh okay my bad
you can modify it
just dont use modmail and contact users directly
Tickets supremacy
not fun
and don't have to pay for features you can make too khmMEE6
innit ashely
write my name correctly for once, someone 
ashely
how are you ashely from discord
its not funny?
....?
just one of us would have a server computer, that guy would literally be rich
we can all make MEE6
i dont have
me not the dashboard but someone would make that
i paid for mee6 once and it's been premium for 2 years now
it's forever premium their payment system is broken
why did you do that?
did i do what
its garbage
I can't even integrate payment services cuz I live in russia 💀
objective
The Russia is good the Putin is Bad
y'all unlucky
Putin is good russia is bad
pfftttt
am i right?
You are all wildly off topic
nah ur opinion is invalid cause u have turkey flag as ur pfp
Pretty sure politic discussions are against the rules as well
is anyones changeprefix dont work?
o sorry im quiting
now this wasn't the bot helping u
bye
u stalking
sorry boss
is anyones changeprefix dont work?
Correct, I am actively more involved in the channel (more than previously)
||knew it
not even the bot can match the amount of free time you got||
We all have different change prefix commands lol
If you mean that
dude's stealing your ot job
but mine isnt working
Show the code
okay
yeah show the code sebaztian
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
file_directory = os.path.dirname(os.path.realpath(__file__))
def get_prefix(Client, message):
with open(file_directory + './databases/prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
def get_prefix(Client, message):
with open(file_directory + './databases/prefixes.json', 'r') as f:
prefixes = json.load(f)
if message.guild: #checks if the message was sent in a server or not
return prefixes[str(message.guild.id)]
return "." #returns a default prefix if the message was sent in dms
def get_prefix(Client, message):
with open(file_directory + './databases/prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
@Client.event
async def on_guild_remove(guild):
with open(file_directory + './databases/prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open(file_directory + './databases/prefixes.json', 'w') as f:
json.dump(prefixes, f, indent = 4)
@Client.command()
@has_permissions(manage_roles=True)
async def changeprefix(ctx, prefix):
with open(file_directory + './datatases/prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open(file_directory + './databases/prefixes.json', 'w') as f:
json.dump(prefixes, f, indent = 4)
await ctx.send(f'`Serverens prefix er nu ændret til: {prefix}`' )```
that's our Ashley
ley, at last
jesus
i followed a video
Oh no
hmmm
and it worked for a week ago
./databases/prefixes.json the most controversial path I have seen today
3
should i delete 2 of them
the first two
you do know that the get_prefix on the third position will only be run
anyways, bye, match started, goodluck meh and exenifix and 𝗡𝗮𝗺𝗲 
the first and last one
sebastian finsterwalder
@proud rain use a proper database, for example sqlite or postgres
i deleted two of them now
make sure to leave the correct one there
i did
that's a terrible tutorial
Is it?
ok
Yh i rate it 2/10
Ok thx

Is there any example code for local prefix caching for discord bot?
interesting
Like using a .env file?
Not entirely true, also storing api keys in json file is a bad idea
especially unhashed
but how can i fix it?
Just create a dict with ids as keys and prefixes as values and update the dict when you fetch the prefixes
No, like locally storing prefixes to prevent io bound calls to the database
That's basic caching
Yeah, I kind of made it myself
https://mystb.in/BaltimoreTheeGroup.python
felt a bit... lacklustre if you will
more like alot of features missing
Yeah the __main_cache right?
yes
I can set up pg NOTIFY to register changes or use hasura to make a webhook that registers remote changes
but too much work to do from scratch 
i got it from a tutorial on youtube
😔 GitHub is down
didn't have anything else on my mind
Really?
Yea
Was working fine for me lmao
Oh well
pyweek?
What’s pyweek lmao
valorant
Lmao
😔
lmfao
ah ik its cringe but yea my sis on discord now so gotta act like ima nerd
waitt hunter has the same

ima change before i become hunters clone
😔 Stop
Thanks
Hey !
Trying to make a discord bot. I have a command named get.
Inside, i have a ```py
msg = await ctx.send("my message")
I'me trying to add 1️⃣, 2️⃣ and 3️⃣ to that message but couldn't find a way to send that reactions.
Can someone help me ?
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
yeah, but, as they are unicodes emojies, it doesn't works, do u know how to do ?
!charinfo 1️⃣
\u0031 : DIGIT ONE - 1
\ufe0f : VARIATION SELECTOR-16 - ️
\u20e3 : COMBINING ENCLOSING KEYCAP - ⃣
\u0031\ufe0f\u20e3
yeah, i tryed x)
look at the full raw text and copy it. Do the charinfo command for the other emojis in #bot-commands
copy the full raw text in the above embed
thks, and, do u know how that command works, to be able to do it "myself"
type !charinfo [emoji] in #bot-commands
[emoji] is a placeholder value for the emoji you want to get the character information of
Bruh for some reason discord is crashing repeatedly
ok, ill try and say u if it doesn't works
Huh?
what?
aaaarg, it doesn't works !
Error : RuntimeWarning: Enable tracemalloc to get the object allocation traceback
you have not put await somwehere something
send the full traceback
uhmm
just because i didn't put that ???
😔 Thanks discord, not when I try to use the backslash button the app crashes
thaaaaaaaanks it works !!!!
Why is my buttons not sending?
the code would help
anybody know how to actively import code from a seperate python script to the discord bot? im looking for active updates when i run a command but instead the bot will not start until the script its importing from is done (its while loop until i disable it) which completely defeats the purpose of active feedback :p
@Client.command()
async def button(ctx):
await ctx.send(
"",
components = [
Button(style=ButtonStyle.red, label = 'test!')
]
)
interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
await interaction.respond(content="test")```
My buttons dont work?
someone who can help
which lib
and for buttons?
nextcord i think
huh
😔 I will leave it to Raven to help u
why not use discord.py for buttons?
you do know that discord.py has buttons...
not before now
what version are you using
did you just do pip install discord?
pip show discord.py in terminal
1.7.3
you should probably upgrade
how to
if you want you can uninstall it and install again
still dont fix
Here is an example of using buttons https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
not working :(
what ide are you using?
look at the example for buttons
Hey uhh so this doesn't send the image, why?
@animals.sub_command()
async def cat(self, inter):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.thecatapi.com/v1/images/search?api_key={cat_auth}") as resp:
data = json.loads(await resp.text())
catEmbed = disnake.Embed(
title = "Cat!"
).set_image(
url = data[0]['url']
).set_footer(
text = "Powered by The Cat API")
await inter.response.send_message(embed = catEmbed)
No errors
can u print url?
Ok
what does pass_context do?
Old code
basicly passing ctx as argument?
Lemme test
Yea if its set to true then the ctx arg is passed else not
hmm
It fixed itself magically
Lmao
I don't know how but it did
anybody know how to actively import code from a seperate python script to the discord bot? im looking for active updates when i run a command but instead the bot will not start until the script its importing from is done (its while loop until i disable it) which completely defeats the purpose of active feedback :p
What do you mean?
so
basically im importing a few variables from a script running a while loop
every loop the variables increase by 1 so thats why i wanted an active variable
but the bot only ever goes online when the while loop is ended
aka the while x = y is no longer true
Hey @candid veldt!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I have a problem when I try to start the bot I get this error:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Moderation' raised an error: NameError: name 'tasks' is not defined
code: https://paste.pythondiscord.com/denegayife
did u import tasks?
from discord.ext import tasks
Next error:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In guild_id: Value "Ellipsis" is not snowflake
show the whole traceback
remove ... and put in a proper ID
value=discord.utils.format_dt(round(user.joined_at.timestamp()), "F"),```
```AttributeError: 'int' object has no attribute 'timestamp'```
not sure how to resolve it..
user.joined_at only
No need for timestamp()
😔 background sucks
All traceback:
Traceback (most recent call last):
File "C:\Users(file name)\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "F:\test bot\cogs\Moderation.py", line 147, in on_ready
self.guild = await self.bot.fetch_guild(...) # You server id
File "C:\Users(file name)\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1188, in fetch_guild
data = await self.http.get_guild(guild_id)
File "C:\Users(file name)\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In guild_id: Value "Ellipsis" is not snowflake.
its a tutorial i think
Hmm nah
So it is unfortunately(oops)
I told u the issue ¯_(ツ)_/¯
What's the shortest string i could turn a guild id into while keeping every guild unique
bro the error says it all
ellipsis isnt a snowflake
okay thanks
What are you doing
Use discord guild IDs?
If a person from a guild wants to attack another they'll have to type an identifier
how can i do slash (/) commands? Like probot, mee6 and more?
i think ill probably make it so they can only attack ones on the leaderboard so itll just be buttons
discord.py supports slash commands, read into the gist on resuming dpy development for examples
@slash.slash(description="Start Game.")
async def mine(message):```
You can do slash commands in discord.py 2.0, you just need to install it from main
The d.py readme in github has instructions on how to do that
How do i fix the Cannot write to closing transport thing?
just want to confirm, is github working?
I am trying to host my bot, but it isn't working
heroku
that sounds like a plan for disaster
the best way I have found to host discord bot's cost effectively is to buy an rpi and run it on that
super low power and it's all you need
I wouldn't recommend 3rd party extensions, quite frankly 99% of them suck
Heroku is not very good, consider switching to an actual host
so I used to do this to set up my botpy async def start_bot(self): await self.connect_postgres() for extension in self.config.initial_extensions: ...and now I'm doing this https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/utils/services.py#L137-L163, should I connect to my postgres db from my setup hook or from the main function?
Both work, before the setup function we did it within the main
But the setup hook makes it easier now
so both work but is the setup hook the more 'recommended' or more 'pythonic' way to do it? or does it completely not matter at all
There's no method that's recommended or Pythonic
By that I mean it doesn't matter
But if you're an organized person you'd probably like the main function better
To have a defined starting point as the very last thing in your file instead of a hook somewhere within your code
okay I'll put it in main then (i'm not a very organized coder but I'm trying to be as organized as possible for tis project to make it scalable with the least amount of input from me as it grows. So now should I connect to the db from inside the async with self or not and from within the async with aiohttp.ClientSession() as session partpy async def main(self): # so here async with aiohttp.ClientSession() as session: # here async with self: # or here print( '------', 'main func', ) for extension in self.config.initial_extensions: try: await self.load_extension(extension) print(f"Loaded {extension.title()}") except Exception: print(f"\nFailed to Load Extension {extension}\n{traceback.format_exc()}\n") self.session = session await self.start(token)
https://paste.pythondiscord.com/omibezujeb Why does my help command just return 1 random cog in the command
Anyone please
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)
if member is None:
await ctx.send("Выберите участника")
return
if reason is None:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
base.commit()
print(2222)
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
base.commit()
cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
not working. Nothing output excepting 45 and 1, why?
channel = await categ.create_text_channel(name=f"{interaction.user.name}-{}".format(ticket_number), overwrites=overwrites)```
I can't fix this. if I remove the f string `interaction.user.name` won't work but if i put the f string `{}` the error `empty expression not allowed` comes
pls paste the whole tb
can you do ```py
@commands.command(description='this command is sus')
async def sus(sus_self, sus_context, sus_param):
print('sus')
sure
and by that i mean, can you put a command description like that?
Either use an fstring OR .format, not both
sure
!string
nice
.
!strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
#bot-commands
..
I can't
i cant copy it atm smh my phone wont let me
Remove the .format, and put the thing you want to put in the string inside the {}
Then please show the whole console
where r u changing the presence in yr code?
No thanks I don't wanna kill my eyes tryna read that 
whenever it plays a new song
The point will be lost, I am trying to make it so it creates a channel #BedrockEdition-1 then 2.. and goes on
when it plays a new song it changes its status to the song name
ok hold on let me try something else
@south jetty Still the same thing
f"{interaction.user.name}-{ticket_number}"
yes, realized few mins ago
ok so now I am trying to stop the bot from making multiple channels.
if ch.name==f"{interaction.user.name.lower()}":
await interaction.response.send_message("You already have a ticket opened!", ephemeral=True)
return ```
wait what is ```py
async def main(self):
async with aiohttp.ClientSession() as session:
async with self:
async context managers creating an aiohttp session
what exactly would I need to use to identify that someone already has a ticket
use a database
how can my bot online ?? (haha you can't see my token
bro you know theres a run button on your top right?
and it wont run its on your ready event
it should not be in any funtion
you need to unindent line 13, or it won't run
You should also remove the extra blank line on line 7
3 extra lines for no reason in the same function
but my cmd didn't print bot is online
did you did what was said?
yes
show code
bro
^
^
You still need to unindent bot.run(...)
It's inside the on_ready function, which won'
t run until the bot has started
🤔
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
how do i fix that cannot write to closing transport thing ?
What
something really minor
how on earth do i run multiple python scripts at once
i dont even need threading since i have an ext database
yes, this is an incredibly dumb question
but i need an answer anyways
It's so simple sorry i am noob :(
Dont be sorry 😄 
bro you had everything right you just need to delete 4spaces/an indent level
Actually i am just 13
doesnt matter
;)
being young doesnt mean you cant code
🥰🥰🥰
oki was coding since he was 1, so you can surely code since u r 13 (:
yup
I've made a badge-list, but when i test it on a user without a badge it says In embeds.0.fields.1.value: This field is required
and i want to make it so it doesn't add the field for users without a badge, any ideas?
badgelist = ""
if user.public_flags.hypesquad_brilliance:
badgelist += f":brilliance: Hypesquad Brilliance\n"
if user.public_flags.hypesquad_bravery:
badgelist += f":bravery: Hypesquad Bravery\n"
if user.public_flags.hypesquad_balance:
badgelist += f":balance: Hypesquad Balance\n"
e.add_field(
name=f"**Badges**",
value=badgelist,
inline=False,
)```
!?
if not set([FO, HC,GM]).intersection(set(message.author.roles)):
return await message.channel.send("You have no access to this")
That's not where the error is coming from
Send the Full traceback
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/bot1/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 427, in on_message
if not set([FO, HC,GM]).intersection(set(message.author.roles)):
File "/home/runner/name/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1262, in decorator
result = command(*args, **kwargs)(func)
File "/home/runner/name/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1433, in decorator
return cls(func, name=name, **attrs)
File "/home/runner/name/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 217, in __init__
raise TypeError('Callback must be a coroutine.')
TypeError: Callback must be a coroutine.
instead of "+=" use global keyword
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
tell people to use globals
globals bad

atleast its better than "+=" 
not really

its bc of this



