#discord-bots
1 messages Β· Page 528 of 1
ye
Can you please give me an example of how i run flask in the background of my discord bot
if i just scrolled down like 2 lines i coulda saved all that time
that was so magical
seeing the bot go online
how do you see if someone either joins through a vanity link or a bot joins through OAUTH2? I'm trying to make it so that in my invite tracker bot, it shows whether that person joined through oauth2 or vanity
why
Command should not be indented iirc
Prob on invite tracker dashboard π€
its being intented incorrectly
^
And you donβt need line 6 π€
why?
the @bot.command arguments should be intented correctly
@bot.command should @Bot.command and indented
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
Its indents but ok
uh
huh?
im at this, so do i remove line 6?
Add it, in keep_alive file instead
no i mean like to see if someone joined thru vanity or not
@client.event()
async def on_ready():
print('Bot is ready.')
@bot.command(name="hello")
no wtf?
how would i handle it
you just said
dont remove shit
Actually , client.command since they are using client as their commands.Bot var
@weary gale this is your code after indent correctly
oh
so i do that?
@boreal ravine help me with this rq
in the same place?
*```py
@client.event()
async def on_ready():
print('Bot is ready.')
@client.command(name="hello")
do i replace my old one with that?
Sure
Just tap backspace before that @bot lol
yeah they were both talking to me
@slate swan
@client.command() is correct
im confused what ur tracking for the user or the bot?
lets replace with his code
I get some errors on replit.com but I don't see those errors when I use Pycharm
They are runtime errors
What should I do, I am not even able to let my script running because of that error
how would I handle it if the user joined through a vanity invite
for example
etc...```
same thing with oauth
@tropic briar python version error just switch to another repl I think
Ok
what the actual
Or do @raven peak
async def Hello
await ctx send βReplyββ
hOw dO i gEt tHiS tO wOrK
@boreal ravine something like this
i mean ur gonna have to check if the user joined through the vanity but idk how to do that
And the stuff you had under the command ofcoursepy await ctx.send("hello")
Does that work, for a disc bot how?
y do u have 2 on_ready events
yeah thats what i was asking lol
You donβt need either, lol
idk
wdym, its implemented but if the inviter == None, I want it sothat it actually catches if the person joined through vanity or oauth
meaning?
@boreal ravine
@weary gale replace
@client.command(name="hello")
to:
@client.command()
async def hello(ctx):
pass
ok
You could add the Bot online etc, to keep_alive file instead
thats an event
Or, use @raven peak
dude, you really should learn python before you dive into discord.py
this supposed to work?
i dont see how that relates to his question
use quotes or codeblocks while using @bot and others with @ or you'll end up pinging someone
yes
@regal sparrow yes
same thing though
use proper formatting
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
You donβt need on_ready, if you have it in keep_alive
doesnt work when i run the command in my server
Anyone know where is the problem?
@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
if opcion1 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
if opcion2 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
else:
eleccion = random.choice(opcion1, opcion2)
await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")
I have this error choice() takes 2 positional arguments but 3 were given
did u do $hello
yes
@marsh depot try this:
@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
if opcion1 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
elif opcion2 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
else:
eleccion = random.choice(opcion1, opcion2)
await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")
or:
@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None):
if opcion1 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
elif opcion2 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
eleccion = random.choice(opcion1, opcion2)
await ctx.reply(f"**{ctx.author.display_name}** elijo **{eleccion}**")
Is $ your default prefix?
try not spoonfeeding
nothing
oh makes sense why it didnt output anything
he did pass
what
@boreal ravine i used this
yes we know
that was an example lol
read the code
AttributeError: 'Member' object has no attribute 'has_permissions'
modRoles = data['modroles']
for role in ctx.author.roles:
if role.id in modRoles or ctx.author.has_permissions(administrator=True) or ctx.author.id == ctx.guild.owner:
return True
return False```
trying to make a check for a command which sees if user has a role in a db, has admin perms, or is the guild owner
u did pass
what am i supposed to put there
What do u want ur bot to output?
yes pls say
hi
are you really that new
dude,
you gotta learn python first...
discord.py is a terrible way to start
yes
cool
people out here saying it'll take months
!resources @weary gale
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
replace pass with await ctx.send("Hi")
thx
spoonfeeder
yes
!d discord.abc.Messageable.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
π
chad
u only need like a week or 2 of practice
still not working
how??
bro did u even invoke the command
whos that
did you do
client.run("TOKEN")
you need to run the bot
i did
he did
did you save the file
u
restart the bot
does the bot become 
y e s
do you have message intents on?

that aint a thing yet
what?
it was a thing like 3 months ago
restart
admin
I mean u dont need message intents
how
for a command like that
did you write exactly: "$hello" because it's case sensitive
how..?
just close the script and rerun
yes
just kill terminal, close vsc and open it back up
ok
also those r for verified bots.. or bots in 100+ servers
did they change it?
cus i never heard something like this?
o i know what is wrong...
change @quaint axle.command() to commands.command()
BRO
LMAO
python <file>

JSUT STOP
stop
???
everyone stop with these advices
the command
no to open vsc
huh
oh my god
i thought u opened from cmd in the file.

ok whatever
just
python yourfilename.py
^
in cmd
yes
console*
huh
or shell whatever
everyone just stop helping @weary gale
they need to learn python and how the shell works before they use discord.py π
everyone gets help
i dont want to wait a week before i can make a command that says HI
yes learn basic python first
it works
Before learning discord.py, you should know all of these in Python first!
variables
scoping
functions
asynchronous programming
classes/oop in general
decorators
subclassing/inheritance
type-hinting
imports
``` -R. Danny
so thats cool
typehinting isnt really required
go to the green site
cringe

cringe?
relax
Is the same code lmao, and the error i have is this
choice() takes 2 positional arguments but 3 were given
its jsut the cold, hard truth
what did u type for the command in the channel?
don't put args
put those in a list
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
Based
The code and the error
biased?
sounds gay
Hello. In which channel can I get help with discord.py?

this one
Python discord => discord bots => discord.py
^
Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: <module>)
As of 3.10, the loop parameter was removed from Event() since it is no longer necessary
class BotTask(commands.Cog):
def __init__(self, bot, prefix):
self.dblpy = dbl.DBLClient(self.bot, self.token) ##This line
hm
full error?
Exception has occurred: TypeError (note: full exception trace is shown but execution is paused at: <module>)
As of 3.10, the loop parameter was removed from Event() since it is no longer necessary
File "C:\Users\kaspa\OneDrive\Desktop\Python Discord\app\task.py", line 18, in init
self.dblpy = dbl.DBLClient(self.bot, self.token)
File "C:\Users\kaspa\OneDrive\Desktop\Python Discord\main.py", line 93, in <module> (Current frame)
bot.add_cog(BotTask(bot, PREFIX))
I've never seen anything like that
This is just a python 3.10 deprecation error
bot the documentation tells me about setting
self.token to 'dbl_token'
as error says they removed the loop parameter from Event()
I would suggest downgrading from 3.10 unless you want to go edit the internals of discord.py
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
db = sqlite3.connect("database.db")
cursor = db.cursor()
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
cursor.execute(f"SELECT message_id FROM ticket WHERE guild_id = {self.client.get_guild(payload.guild_id)}")
wynik = cursor.fetchone()
if not wynik:
return
else:
for x in wynik:
if payload.message_id == wynik:
if payload.emoji.name == ":white_check_mark:":
await member.send("Utworzyles ticketa!")```
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "/home/kr3mu/.local/lib/python3.9/site-packages/nextcord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/kr3mu/Dokumenty/DiscordBOT/TicketSystem/ticketcreate.py", line 66, in on_raw_reaction_add
cursor.execute(f"SELECT message_id FROM ticket WHERE guild_id = {self.client.get_guild(payload.guild_id)}")
sqlite3.OperationalError: near "Server": syntax error
even tho...
you shouldn't use f-strings for executing something in a db
@slate swan #databases message
fyi this is blocking
!pypi aiosqlite π€·ββοΈ
and you're already getting the guild object, so why are you getting it again when executing
wait
idk what ur doing lmao
File "/home/Mechanic/cogs/giveaway.py", line 346, in giveawaytask
message = await giveawaychannel.fetch_message(msgid)
File "/home/Mechanic/.local/lib/python3.8/site-packages/discord/abc.py", line 1132, in fetch_message
data = await self._state.http.get_message(channel.id, id)
File "/home/Mechanic/.local/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
what is this error?
You are attempting to access message data likely without the correct permissions.
it does not have the perms to what ur telling it to do
why not to add admin perm? noone know
The list of perms should be enough I guess.
well the guild owner dont want the bot to have admin perms
why would the bot need admin perms?
i thought so too but idk something is missing
send ur code
so that all perms are at once and there are no problems with them
async def giveawaytask(self):
for key in self.giveawaychan.keys():
guild = self.bot.get_guild(int(key))
try:
msgid = self.giveawaychan[str(guild.id)]["giveawaymessageid"]
chid = self.giveawaychan[str(guild.id)]["giveawaychannelid"]
time = self.giveawaychan[str(guild.id)]["time"]
except KeyError:
return
giveawaychannel = self.bot.get_channel(chid)
message = await giveawaychannel.fetch_message(msgid)```
that for loop seems really useless
yea idk why its sending that error
hmm
might be how you added the bot to the server
but that's just a guess
on google it said something about syncing perms with the category but idk if thats the case here
channel perms*
for the bot role
those perms are guild specific and not for the channel you are trying to get message from , maybe try check the channel perms
yeah , you can try viewing the guild by bot's roles and see if you can see the channel if you are an admin in the server...
how can i get the channel perms for a role?
If you are doing it through the Discord interface, you can just right click on the category, then Edit Category, then Permissions. Not necessarily sure how you'd achieve it through D.py.
i am doing it with a command
!d discord.TextChannel.permisssions_for i dont think you can do it for a role , but this may be helful
No documentation found for the requested symbol.
!d discord.TextChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
i myself dont have perms to look into server stuff
oh , you can use roles
Why the bot only take the first word?
My code
@bot.command()
async def choose(ctx, opcion1=None, *, opcion2=None): # COMANDO CHOOSE
if opcion1 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
if opcion2 is None:
await ctx.reply(":deny: Debes agregar dos opciones entre las que quieras que elija")
return
else:
select = opcion1, opcion2
eleccion = random.choice(select)
await ctx.reply(f":Loading: Elijo `{eleccion}`", mention_author=False)
because thats how the arguments are passed
How can i solve it?
i would use wait_for to get the arguments. have the user run the command, then ask for the first one and after the second
and if i want to make all in one string? like my code?
ello
i also read it lmao
what documentation?
looks like this one
found it nvm
discord event? https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
Aind if i put
async def choose(ctx, *, opcion1=None, opcion2=None):
send me the error message
How can i solve it? Ayone can help me?
what is Members.Intents and how do i enable it
On discord development portal, switch it on, then save.
okay, but how can i make the bot send all the first option?
Let me test something
I think you can't make it so it takes 2 basically inf arguments
It would probably only work if you make like it like
-choose hello1 hello2
@marsh depot what you possibly could do is make it 1 argument
async def choose(ctx, *, opcions=None):
and than command would be like: --choose the first thing to choose of , the second thing to choose of
and by the comma you can split it into 2 args by
opcion1 = opcions.split()[0]
opcion2 = opcions.split()[1]
this is the only way of having 2 infinite arguments I think
they don't track data
They just track members
do i need to do member.name for the name to print
intents is literally you as the bot owner telling discord what event data you want to get sent
you have all the events
and every event is bound to an intent
If your bot tracks server members or downloads the entire member list, you may need the server members intent to receive member events and the member list.
if you enable the intent you get the events
if you don't enable it you won't get the events
yeah so the events and list
That was well made
yeee thx
I hate having to type an extra line of code everytime I create a command (await bot.wait_until_ready()), anyway I could make things a bit more easier and not have to type that everytime I create a command?
U dont need to type that in commands (I never did)
+1
I have to cuz if I don't, my bot doesn't work
......?
weird
Can't really happen tbh bro
something about the cache not being populated
Its an error or something?
no
Then?
it's the problem, the error is that it simply refuses to get guilds / channels / users without that extra line
Well that error generally comes when yr bot is too slow to start
like it'll return NoneType object
instead of returning a guild object
or whatever it was told to get
Can you show your code?
it's too large
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
well here's part of it
@bot.command(aliases=['ge_addchannel'])
async def guildedit_addchannel(ctx, guild_id, name, type):
await bot.wait_until_ready()
if ctx.author.id in dev_access:
if type.lower() == "text":
guild = bot.get_guild(guild_id)
await guild.create_text_channel(name)
await ctx.send(f"Created a text channel named **{name}** in guild **{guild.name}**")
elif type.lower() == "voice":
guild = bot.get_guild(guild_id)
await guild.create_voice_channel(new)
await ctx.send(f"Created a text channel named **{name}** in guild **{guild.name}**")
else:
await ctx.send("Invalid channel type! Use `devdocs com:guildedit_addchannel` for a list of valid channel types")
else:
await ctx.send("You don't have permission to run this command")
this command doesn't work without line 2
Well yea, understandable
That issue generally comes when yr bot starts too slow
Cz of low resources/slow net
Try waiting a little bit before using the command.
Isn't that what he's doing....?
Or, you can use cogs.
Fair enough, but some commands seem to work fine even if I don't wait
Because in that command you are trying to get a guild from the bot's cache.
Wait, iirc, dpy uses on_message to check for a message with a command, right?
Correct.
Sooo, he can subclass bot and do something like
class MyBot(commands.Bot):
async def on_message(self, message):
await self.wait_until_ready()
return await super().on_message(message)
No?
That would wait for the bot to be ready before listening for messages? Idk
Still repo showing HTML?
And agreed, making docs is tiring and boring
GJ
I need to find someone who will destroy their sleep schedule to write docs for me
π
I have a question, because if you try to use 2 different commands at the same time bot wiil firstly compute the first command and than the other, can it be optimized by multithreading cogs or anything ?
it would?
That's what async is for though.
I'mma pass that one
It's to prevent tasks from blocking each other.
My sleep schedule is already fucked up
It should, yea
I fixed my sleep schedule yesterday since school starts tomorrow.
Well, I go to school half asleep lmfao
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [β@everyone](mailto:'%40everyone)β role.
These roles are sorted by their position in the role hierarchy.
#bot-commands if it's not related to the topic.
Anyone know how can i make bot send a embed with all the emojis of the guild?
I try
@bot.command()
async def emojis(ctx):
emojis = bot.get(ctx.guild.emojis)
await ctx.send(emojis)
But nothing happens
emojis = ctx.guild.emojis
!d discord.Guild.emojis
All emojis that the guild owns.
the same result
Wrong person bro
commands.Bot has no attribute called get.
....?
Oh, my bad.
i change it and get the same, nothing
....?
@slate swan You can use cogs. They're the best way to prevent most cache issues and also to stay organized.
What does it send?
What does it log in the terminal?
@bot.command()
async def emojis(ctx):
emojis = ctx.guild.emojis
await ctx.send(emojis
Nothing JAAJAJA
U forgot a )
is in the code
Do you have emoji intents?
I already use something similar
i think yes
is in the code but i forgot to copy and paste well
Do you have discord.Intents.default()? They include emoji intents.
!d discord.Intents.emojis
Alias of emojis_and_stickers.
Changed in version 2.0: Changed to an alias.
yes
Try printing emojis instead of sending it.
i have this
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix ='--', intents=intents, help_command=None, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False)
(<Emoji id=860902665630646283 name='menfadao' animated=False managed=False>, <Emoji id=860902666242228254 name='pana' animated=False managed=False>)
It returns a list of discord.Emoji object.
Exactly
how would i make it so my bot adds a reation to the users messages letting them know its getting verified like this? https://hastebin.com/osixukipub.py
To print the emoji itself, print([f"<:{emoji.name}:{emoji.id}>" for emoji in emojis]).
It should work.
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add 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.
and if the emoji is animated? how to check if is animated ? i know you need you put an a infront of emoji.name
<a:{emoji.name}:{emoji.id}>
!d discord.Emoji.animated
Whether an emoji is animated or not.
Disthon commits be like
and we're far from being even done
we've got so much to do
get on the grind
we're with a team btw
I went through a bag of coffee beans
lol nice
pypi?
Print all the emojis, but dont send it
Now make it send it.
<generator object emojis.<locals>.<genexpr> at 0x0000024F11E22F90>
@bot.command()
async def emojis(ctx):
emojis = ctx.guild.emojis
listaemojis = ([f"<:{emoji.name}:{emoji.id}>" for emoji in emojis])
print(listaemojis)
await ctx.send(listaemojis)
use join
ΒΏ?
remove the () around the list generator
Print that i want, but dont send anything
listaemojis = [f"<:{emoji.name}:{emoji.id}>" for emoji in emojis]
this is i make
no, you have brackets
i change it lmao
remove those
he tell me and i change it
so it works?
Print this but dont send anything
remove the ctx.send line?
I've just read the whole conversation to understand
Im trying to make an app that verifies roblox users, however it is not working.
No error persists, it just ignores this;
if user == verstr:
await ctx.send("Verified")```
Full code:
```py
def get_ro_info(x, info):
user_req = requests.get(f"https://users.roblox.com/v1/users/{x}")
user_json = user_req.json()
usr = user_json[info]
return usr
possible_words = [
"Happy ",
"Police ",
"Gun ",
"Developer ",
"Dog ",
"Squid ",
"Cat ",
"Horse ",
"Cow ",
"Pig ",
"Brick ",
"Pans ",
"Blocks ",
"Roblox ",
"Robloxian "
]
def make_sequence(seq):
if seq is None:
return ()
if isinstance(seq, Sequence) and not isinstance(seq, str):
return seq
else:
return (seq,)
def message_check(channel=None, author=None, content=None, ignore_bot=True, lower=True):
channel = make_sequence(channel)
author = make_sequence(author)
content = make_sequence(content)
if lower:
content = tuple(c.lower() for c in content)
def check(message):
if ignore_bot and message.author.bot:
return False
if channel and message.channel not in channel:
return False
if author and message.author not in author:
return False
actual_content = message.content.lower() if lower else message.content
if content and actual_content not in content:
return False
return True
return check
def verifystr(x, y):
return ''.join(random.choice(y) for z in range(x))
@bot.command()
async def verify(ctx):
authr = ctx.author
await authr.send("Please send me your roblox ID:")
response1 = await bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
verstr = verifystr(10, possible_words)
await authr.send(f"Please put this in your About Me and DM me `DONE` when done:\n{verstr}")
response2 = await bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
if response2.content == "DONE":
user = get_ro_info(int(response1.content), "description")
if str(user) == str(verstr): # <<< code in question
await ctx.send("Verified")
else:
await ctx.send(f"Not verified {verstr}")
await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
await ctx.send(user)```
If you found out why it doesnt work, please mention me!
what
send an error or something
there is none
what have you done, what output you got
Just the verification sentence, as well as the BIO of the roblox user, which matched
verification sentence?
sorry, my english isnt super right now as i am sick
yeah, its a phrase you have to put in your Roblox bio, which is randomized each time
mmhm
Whitespace might be the issue, idk
so what exactly doesn't work here
if str(user) == str(verstr): # <<< code in question
await ctx.send("Verified")
else:
await ctx.send(f"Not verified {verstr}")
await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
await ctx.send(user)```
can you print both user and verstr?
await ctx.send(f"Not verified {verstr}")
await ctx.send(response2.content) # Used these messages to look if the strings were the same, and they are.
await ctx.send(user)```
.
print(verstr)```
before the if statement
it looks like the second one has a \n at the end
I wouldn't wonder if that would be the issue
doesnt print automatically go to the next line
idk
yes'
it does
I would check for
if str(user).strip("\n") == str(verstr).strip("\n"):
alr
nope, doesnt resolve the issue
what are those ------
from on_ready
@client.command()
async def ownercheck(ctx):
await ctx.send(ctx.guild.owner.mention)```
How is ctx.guild.owner a nonetype here??
!d discord.Guild.owner
property owner: Optional[discord.member.Member]```
The member that owns the guild.
I don't know, must be something different there
a space at the end for example
this is not a server that sells bot, make a code and ask for help, we are not going to spoonfeed you
hi
i have a command group named whitelist, it shows how to add/remove and the current whitelist
add adds the role to a db,
remove removes it from the db,
i have the EXACT SAME code, but for moderator roles,
add adds the role to a db,
remove removes it from the db,
when i invoke *modroles add @Moderator#8006_role; it works as expected
but when i invoke *nicknamewhitelist add @Nickname#1234whitelist_role; it says role is a missing paramater
i changed the sub command of nicknamewhitelist to add1 and it works as expected
can you not have 2 sub commands in different groups be the same?
How do u request for someone's profile from that api
Never seen anyone use the roblox api here
are you using member obj?
and you take a member obj as a argument, right?
No
I have to use discord.ext
for that but it isnt working for me
I am using repl.it
why can't you use a member obj? It should still work with replit
async def(ctx, member: discord.Member):
``` did you do smth like that?
you use on_message for mute?
Yeah
are trying to make a antispam?
No a mute
you are trying to make a command with a event? Why's that?
I tried to use something like this
@client.command
def mute():
pass
but it didnt work
you need to add arguments
@client.command
def mute(ctx, member: discord.Member):
await ctx.send(f"{member} got muted")
``` example to run it `!mute AnyMemberID` or you can mention it (the user)
{member.name} = members name
{member} = membername#0000
ig u r looking for this.
how can i IMPORT DISCORD
import discord
pip install discord then import discord
isn't it pip install discord.py?
in powercell?
well anywhere you like to run the pip install
they are 2 different packages (that should have the same code tho)
oh
its still not working
What's the error
did you add python to path?
yeah
What's ur python version?
this
3.9.6
TypeError: on_message() missing 1 required positional argument: 'member'
try pip3 install PackageName
can you show code for this?
show the code
OK
same error
i recommend asking in #python-discussion
Hey @solid wave!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
paste it to the link
remove member: discord.Member at on_message event
ok
and use @client.command() for commands and not a event
thats really bad to use a event for commands
()
my bad, fixed

This code gives me pain
which one?
This
oh
All rights reserved. Seriously if you try to copy me I will hack you I know how to do it. And you will never see me coming.
what the actual duck
π¦ , this duck
I hope nobody copies this
hahah that's satire I hope
I was not going to
why not
why not be friends
imagine asking someone to be friends and then telling him that you don't want to be
Friends are bad
Too big change of social contacts
.topic
Suggest more topics here!
what is this
a topic
Don't force slash commands
true
@solid wave , did you get what was wrong in your code?
everything
it was so everything, you don't even need a thing
that's how every it gets
why this twice
I was just making sure they know what to change
and on_message doesn't take a member argument
why not
works as intended for sure
person:
!report @slate swan
bot:
reported the heck outta him
discord bots was one of my best projects ever, but sadly everything good ends...
I made a cube shooter in Unity/3d shooter game (which was worse than you can imagine)
I'm currently stuck on not being able to play a flipping animation once
I'm pretty sure I could imagine no offense
How do I give roles based off role names in a JSON file?
So if I make a JSON like this:
{"866057742989131866": {"722905649360666824": ["@everyone", "staff", "admin", "VIP"]}}
How do i give someone those roles
offense taken
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
can i have a commands.cooldown only if a certain thing happens?
i have a command, but if you missspell something after typing the command, it still gives you a cooldown. i want it to only give you a cooldown with an if statement. is that possible?
your iterable is gonna be
guildInstance.roles
and a name kwarg should take the role's name
!custom-cooldown may work for if statement
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
alright ty
np
I'm still a bit confused
Wait let me try to explain what should happen
lemme give you an example
So I made a command where when you mute someone, it saves their roles in a JSON file, and remvoes all those roles. That works perfectly. but how do i return those roles to the user after you unmute them
role = discord.utils.get(ctx.guild.roles, name="Admin")
await member.add_roles(role)
I would definitely use a database
I think i'm having trouble iterating through the JSON file
well somebody else should be able to help with that
definitely not me
cuz I don't know nothing about JSON
Oh, alright
what is your code ?
@client.command()
@commands.has_permissions(manage_messages=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][member.id]:
try:
print(role.name)
thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
await member.add_roles(thing)
except:
pass
I'm definetly doing it wrong
I'm not good with JSON files so
Just wondering why do you manage_messages as the requirement for an unmute command?
I guess because people who can manage messages should also be able to mute ig. i should probably change it to administrator now that i think about it
Or manage roles
So how would I iterate through the JSON file in this case?
{"866057742989131866": {"722905649360666824": ["@everyone", "staff", "admin", "VIP"]}}
``` ^^ The JSON files looks like this
You wouldn't really want administrator for an unmute command
ill change it to manage roles
member.id is an integer and you have it as str in json file mb that's the case
"722905649360666824"
This time it doesn't return a key error, but it doesn't give back the roles
Ghost ping 
I cant help atm, I will go to sleep
oh ok
@delicate moat Does it remove 'Muted' role ?
yup. it removes the muted role so i think there is a problem in my loop
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][member.id]:
try:
print(role.name)
thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
await member.add_roles(thing)
except:
pass
ok so the problem must be here, gimme sec i'll try to debug it
yea, i think the problem is there too
i have a code in my bot similar to this:
array = [id, id1]
for role in author.roles:
if role.id in array:
do something
it seems as if @ everyone is counted in for role in roles, is there a way to exclude it?
Does it give an error because of @ everyone?
I know what happens see when you are reading it those are string and than you want to take name attr from it which string doesn't have
in role.name
so you try to do "Admin".name
u can index the list
you have to get object of the role from the server by name
I thought im already doing that by
thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
add [1:] at member.roles or something
isnt that how lambda works? idk
no but since its for role, if the user has 2 roles, 1 in the array and one not in, itll send 1 success message and 2 error message, (assuming @ everyyone isnt in array)
ctx.author.roles[1:]?
?tag slice
i saw something abt it but didnt know where
yes
alr bet it works, but if a user has 1 role in array and 1 out, itll send the success message, and then the error message, how do i stop it
whats the error?
not an error, just a error message if a role.id is not in error
hm
like maybe a way to break
data = db.find_one({'guild_id': ctx.guild.id})
modRoles = data['modroles']
for role in ctx.author.roles[1:]:
if role.id in modRoles:
if userdata.find_one({"discord_id": member.id}):
epicid = userdata.find_one({'discord_id': member.id})['id']
name = userdata.find_one({'discord_id': member.id})['name']
embed=discord.Embed(title='Query Successful', description=f'des', color=3145472)
await ctx.send(embed=embed)
else:
embed1=discord.Embed(title='Error', description=f'{member} is not linked to an Epic Account', color=16717056)
await ctx.send(embed=embed1)
else:
embed2=discord.Embed(title='Error', description=f'You need to have a mod role in order to do this command. Administrators of the server can configure mod roles via the `{ctx.prefix}modroles` command.')
await ctx.send(embed=embed2)```
@delicate moat So I think correct code should be:
@client.command()
@commands.has_permissions(manage_messages=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role.name, ctx.message.guild.roles)
print(role.name)
await member.add_roles(thing)
except Exception as err:
print(err)
Hmm still doesn't return roles
it prints
'str' object has no attribute 'name'
'str' object has no attribute 'name'
'str' object has no attribute 'name'
'str' object has no attribute 'name'
im assuming thats the error right
o because it's not role.name but thing.name
change this print(role.name) to print(thing.name)
@delicate moat did it work?
It still returns the same thing
k
what does this mean
could you send code ?
i have two files for it actually, its for my modmail
member.py https://hastebin.com/educegoxot.py
mod.py https://hastebin.com/itixapudih.py
when does this error occur?
I have installed discord.py but discord is still marked as an error
when i type something to the bot and when i type back, it also does it for my other server which idk why
for both of commands?
yea
Probably not installed to path
wut path
It's not installed correctly
I just installed it and did everything it told me to do
I'm trying to figure it out because it's quite a lot of code and error that tells me nothing xD
oh
Send the error
it's @outer violet's issue not mine
yea
You should not use Repl.it to host your bot.
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
-
The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
-
You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
-
Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
-
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
So dumb question but: What is the name of that software you can use to set custom statuses, like playing x for x minutes? I used to have it but lost it in my ocean of downloads.
i already know that
It's built in to discord.py
idk what that has to do with my error ;-;
Nothing im just saying
Can you import it
wdym
Can you explain your issue again
when I type import discord discord is grayed out/underlined
@lean storm firstly what IDE are you using?
pycharm
Reload pycharm
okay ;-; so can you help?
I'm a newbie when it comes to this stuff so don't get angry
ok, when you go to file -> settings -> Project: name -> python interpreter , do you see discord
@wheat moth wait why isn't my json dict being deleted?
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
print(thing.name)
await member.add_roles(thing)
except Exception as err:
print(err)
del data["866057742989131866"][str(member.id)]
Like the dictionary with the user id key isn't being deleted for some reason
Yikes
how do I fix
@delicate moat you have to do
data["866057742989131866"].remove(str(member.id))
f = open('roles.json', 'w')
json.dump(data, f)
f.close
idk if that is the best way to do that but it works
shouldn't it be f.close()
ye
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
print(thing.name)
await member.add_roles(thing)
except Exception as err:
print(err)
data = data["866057742989131866"].remove(str(member.id))
f = open('roles.json', 'w')
json.dump(data, f)
f.close()
``` so like this
ye
and also I'm not sure data["866057742989131866"].remove(str(member.id)) will work because it's dict. Give me sec to check it
ye do that
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json', 'w') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
print(thing.name)
await member.add_roles(thing)
except Exception as err:
print(err)
del data["866057742989131866"][str(member.id)]
json.dump(data, f)
it's more elegant solution to do it i suppose
Im pretty sure
del data["866057742989131866"].remove(str(member.id))
``` wont work since its a dict
@bot.command(aliases = ["lb", "baltop"])
async def leaderboard(ctx,x = 10):
users = await get_bank_data()
leader_board = {}
total = []
for user in users:
name = int(user)
total_amount = users[user]["wallet"]
leader_board[total_amount] = name
total.append(total_amount)
total = sorted(total,reverse=True)
em = discord.Embed(title = f"top {x} richest {random.choice(monkeylist)}",color = discord.Color(0xfbff00))
index = 1
for amt in total:
id_ = leader_board[amt]
member = bot.get_user(id_)
name = member.name
em.add_field(name = f"{index}. {name}" , value = f"{amt} banna", inline = False)
if index == x:
break
else:
index += 1
await ctx.send(embed = em)```
why is this happening? it just started giving me this error and I don't know what I did to cause it
@delicate moat I fixed it look now
@delicate moat because I just copied it blindly instead of changing ;-
is it working ?
member is none
Are there any opensource api to use for normal discord.py and not having to convert to slash
I have done some searching but I want an opinion from you guys.
Wdym
All verified bots are going to have to convert to slash commands april 2022
Opensource api's for discord.py? not discordslash.py
@slate swan there are 2 reasons this happens, 1: you gave wrong id. 2: You have to fetch user and in this case you can:
member = bot.get_user(id_)
if member is None:
member = await bot.fetch_user(id_)
How about none-verified
I have no idea what you mean
Non verified bots wont have to switch to slash commands
Oh alr thanks.
If you do end up having to verify you will have to rewrite everything
How are those slash commands working bcs I have one verified bot and idk how to convert him to slash commands in case I have to.
you have no theres no in case, unless you get the message content intent
So what is the difference between normal commands and slash commands in code?
different stuff
Slash commands just straight up have more code
They're pretty similar though
so like instead of ,slap @amber beacon in slash commands it will be something like /slap user:options
This one works because you do f=open(roles.json, w) and f.close()
json is not a database and you should not use it as a database
@delicate moat So this works:
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json', 'w') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
print(thing.name)
await member.add_roles(thing)
except Exception as err:
print(err)
del data["866057742989131866"][str(member.id)]
json.dump(data, f)
Slash commands aren't as powerful as regular commands. And if anything way way more underpowered
They are very limiting
@client.command()
@commands.has_permissions(administrator=True)
async def unmute(ctx, member : discord.Member):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role in member.roles:
bot_delete = True
await member.remove_roles(role)
with open('roles.json') as f:
data = json.load(f)
for role in data["866057742989131866"][str(member.id)]:
try:
thing = discord.utils.find(lambda r: r.name == role, ctx.message.guild.roles)
print(thing.name)
await member.add_roles(thing)
except Exception as err:
print(err)
del data["866057742989131866"][str(member.id)]
f = open('roles.json', 'w')
json.dump(data, f)
f.close()
message = await ctx.send("User has been unmuted.")
embeded = discord.Embed(color = 0xEE8700)
current_time = datetime.datetime.now(pst).strftime("%H:%M:%S")
embeded.add_field(name = f"{member} has been unmuted!\n", value=f"{ctx.author} has UNMUTED {member}\n\nDate: {datetime.date.today()}\nTime: {(current_time)} PST\n\nAdmin ID: {str(ctx.author.id)}\nUser ID: {str(member.id)}")
logs_channel = client.get_channel(896464547588759603)
await client.wait_until_ready()
await logs_channel.send(embed = embeded)
else:
message = await ctx.send("User isn't muted!")
await asyncio.sleep(3)
await message.delete()
await ctx.message.delete()
bot_delete = False
k
I would recommend you to use my method because it opens json file once instead of twice like you do but it is still good.
Am i able to request a bot if so i would like a bot where only admins and certin people can add money to different members of the discord server
could you try to print out list
with print(list) before the 'if len(list) < 0'
@potent jetty
also you may want to call it list_ because list is also a variable type and they may conflict at some point
does it print out anything?
before the error
@client.command(aliases=['sexy'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
subscribers = await ctx.guild.premium_subscribers()
boosters = ""
if len(subscribers) > 0:
for i, subscriber in enumerate(subscribers):
boosters += f"\n`{i}` {subscriber.name}#{subscriber.discriminator} `({subscriber.id})`"
embed = discord.Embed(title=f":boost: __boosters__" ,description=boosters ,color=0x2E3235)
await ctx.send(embed=embed)
@potent jetty try using this
I changed some variable names so they make sense and may work
where is the bot hosted?
ye because you get your errors on the chat not in console or anything
Could you disable the error handler for sec just comment it out or anything
because I would like to know the actual error
what is above that
.premium_subscribers is a property that's why you're getting an error
It's not a method which you can call
Oh yeah, that's it. I find it quite weird that there was nothing about this line in error msg
Although there maybe was something above what he sent
They indeed are above what he sent as that's not the full error
yep, python has like 2 part error.
Yeah
Also it's not a coro so no need to await it, would most likely also raise an error
so it'll be:
@client.command(aliases=['sexy'])
@commands.cooldown(4,15, commands.BucketType.guild)
async def boosters(ctx):
subscribers = ctx.guild.premium_subscribers
boosters = ""
for i, subscriber in enumerate(subscribers):
boosters += f"\n`{i}` {subscriber.name}#{subscriber.discriminator} `({subscriber.id})`"
embed = discord.Embed(title=f":boost: __boosters__" ,description=boosters ,color=0x2E3235)
await ctx.send(embed=embed)
can't you do enumerate(subscribers, 1)
it will start counting at 1
Yeah you can do that too
you could do
@bot.event
async def on_voice_state_update(bot, before, after):
if before.channel != None and after.channel == None:
print("BOT VOICE STATE UPDATED")
You check if you've been in channel before and if you are no longer in channel after
@slate swan
also you shouldn't call first variable 'bot' as it's member not the bot
np
ye
gimme sec i've got to check exactly how
in docs
Use the audit logs
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel != None and after.channel == None:
if member.id == bot.id:
print("BOT VOICE STATE UPDATED")
this is good for the most part but you have to replace bot.id with id of your bot
idk how to get it within discord.py
Just do bot.user.id
@slate swan
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel != None and after.channel == None:
if member.id == bot.user.id:
print("BOT VOICE STATE UPDATED")
yes you can do
try:
await guild.voice_client.disconnect(force=True)
except:
pass
@client.command()
async def xp(ctx):
if ctx.author != client.user:
user_id = ctx.author.id
mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
xpdata = mycursor.fetchall()
await ctx.send(f"Your XP is: {xpdata}")
Why is this command like not working at all? It doesn't send anything, I don't get any errors and nothing like that
try putting a print("works")
in between the function declaration and the if statement so you will see if it's called at all
@client.command()
async def xp(ctx):
print("works")
if ctx.author != client.user:
user_id = ctx.author.id
mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
xpdata = mycursor.fetchall()
await ctx.send(f"Your XP is: {xpdata}")
are you using cogs ?
nope
import mysql.connector
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
thats all without the database part
@commands.command()
async def xp(ctx):
print("works")
if ctx.author != client.user:
user_id = ctx.author.id
mycursor.execute("SELECT xp FROM users WHERE user_id = %s"), [user_id]
xpdata = mycursor.fetchall()
await ctx.send(f"Your XP is: {xpdata}")
try this, i just changed client.command to commands.command
is the bot online when you turn it on and are you writing !xp with all small letters ?
do you have any error handler which may hide issue ?
nope
Well, that's an interesting one.
my on_ready and on_message events work perfectly fine
try to comment out all of the database stuff to see if command will run
I don't know a lot about db so you may need to ask someone else to help you with that one
but at least you know what causes the problem
File "C:\Users\marva\Desktop\sty\main.py", line 42, in <module>
bot.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.main' raised an error: AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'```
import random
import discord
import asyncio
import os
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, SelectMenu
import config
bot = commands.Bot(command_prefix="?")
bot.remove_command("help")
@bot.command()
async def load(ctx, extension):
if ctx.author.id == 888065311289507933:
bot.load_extension(f"cogs.{extension}")
await ctx.send("cogs is loaded...")
else:
await ctx.send("you are not a bot developer...")
@bot.command()
async def unload(ctx, extension):
if ctx.author.id == 888065311289507933:
bot.unload_extension(f"cogs.{extension}")
await ctx.send("cogs is unloaded...")
else:
await ctx.send("you are not a bot developer...")
@bot.command()
async def reload(ctx, extension):
if ctx.author.id == 888065311289507933:
bot.unload_extension(f"cogs.{extension}")
bot.load_extension(f"cogs.{extension}")
await ctx.send("cogs is reloaded...")
else:
await ctx.send("you are not a bot developer...")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
bot.run(config.TOKEN)```
from discord.ext import commands
class user(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.cog.listener()
async def on_ready(self):
print(1)
@commands.command()
async def info(self, ctx):
await ctx.send("hello, world!")
def setup(bot):
bot.add_cog(user(bot))```
thanks
Issue was solved
Ye I know but for the next time.
This is a python server
oop. i copied and pasted to the wrong server, sorry
It's alr
xD
I imagined going to wrong country by accident, sure someone done that but I would love to see his face the moment he realized.
New to the API, still learning.
Wanting help on how to delete the bot's message via a reaction to that same message.
/channels/{channel.id}/messages/{message.id} with DELETE request
Is anyone going to change APIs soon?
if you were to add reactions to embeds would it be this?
await message.add_reactions
yeah i guess
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add 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.
is it because you missed the colons?
i dont know though, havent touched dpy in a while
You have to put the unicode like this \β
\:white_check_mark:
can u give a example
better example*
thats a good enough example
you type it out but put a slash before it, then copy it
ye u can just slot the emoji in
No you have to copy the output that shows up like this: \β
You can also go on this website for example and copy emojis from there https://emojipedia.org/unicode-10.0/
nvm handled the delete reaction myself
it just deletes all of the messages from the bot now because it is defining every sent message instead of the most recent one 
though I could ask for it to delete the message the reaction is on instead of doing that
now it's doing it once 
async def callback(self, interaction: discord.Interaction):
if self.values[0] == 'Warns':
db = await aiosqlite.connect('database.db')
cursor = await db.execute('SELECT * FROM warns WHERE user_ids=?', (member.id,))
rows = await cursor.fetchall()
await db.close()
embed = discord.Embed(
title=f"Warns",
color=discord.Color.red())
for row in rows:
embed.add_field(name=f"Case {row[2]}", value=row[1])
await interaction.response.send_message(embed=embed)
return
if self.values[0] == 'Mutes':
await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)
if self.values[0] == 'Bans':
await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)
if self.values[0] == 'Kicks':
await interaction.response.send_message(f'Currently Not Available!', ephemeral=True)
class HistoryView(discord.ui.View):
def __init__(self):
super().__init__(timeout=5)
self.add_item(History())
client = PersistentViewBot()
client.remove_command('help')
@client.command()
@commands.has_permissions(administrator=True)
async def history(ctx: commands.Context, member: discord.Member = None):
if member == None:
a = await ctx.reply("You can't see the history of nobody!")
await asyncio.sleep(5)
await ctx.message.delete()
await a.delete()
return
else:
view = HistoryView()
embed = discord.Embed(
title=f"History of {member}",
description=
f"Choose the type of history you would like to view!",
color=discord.Color.purple())
embed.set_footer(text="This will time out in 45 seconds from the last interaction.")
await ctx.channel.send(embed=embed, view=view)
await ctx.message.delete()
await view.wait()``` I have this... How can I make it to where in the the tuple in the database, `member.id` works?
i was just wondering, is this possible to make a spoof process for discord to detect, without using change presense like crearinf a fake minecraft process which actually show minecraft icon on discord??
be more clear. are you saying a custom rpc?
so, do you want to insert member.id to db or?
i think they mean a bot with a game like status such as valorant shows the icon and minecraft shows an icon, i think?
:white_check_mark:
No, so the member mentioned in the history command, I need to somehow pull that out and throw it into the callback so I get the modlogs history of that user from the database.
a custom process which discord detect and think that the user is playing minecraft
async def callback(self, interaction: discord.Interaction, member = None): then later put the member to the member parameter
my god am I a moron
I keep disregarding the fact that I cannot use context in this scenario
AttributeError: 'NoneType' object has no attribute 'id', I don't think it's getting the member from the command. Like I use ".history @hollow agate".
welp there's no error coming out
wonder where it decided to give up
oh, you want the member to be passed when an interaction happens?
you can use pypresence for this
Kinda, yeah. I want the user mentioned in the command's history to be pulled up in the database.
How can I please tell, I never used it
wait_for is the issue here 
even if the reaction is added it just ignores it and proceeds to time out
rpc template > https://github.com/tokenlogger/Python-RPC
thx
π
?
that name tho 
yeah thats my friend
.
i dont think you can tho
Hmm, can I put a dropdown inside my command somehow?
Like defining the dropdown stuff inside of the command instead of using a callback?
can't define ctx in the listener because that breaks the listener entirely (expected)
cannot even use the alternative methods
can't you just subclass ui.Select and put it somewhere?
Possibly. I've never used it so I don't know how I can, could you guide me by chance?
sure, but my knowledge is very limited with 2.0
What shall I do xD
That's going to be useful. Thank you!
where will you put it tho?
No clue where even it's possible to put it. So I'm not sure :P
is self.bot.wait_for purely a mistake
in which message? 
Could you explain, I'm so sorry, I just don't understand.
in which message do you want to add the dropdown?
@client.command()
@commands.has_permissions(administrator=True)
async def history(ctx: commands.Context, member: discord.Member = None):
if member == None:
a = await ctx.reply("You can't see the history of nobody!")
await asyncio.sleep(5)
await ctx.message.delete()
await a.delete()
return
else:
view = HistoryView()
embed = discord.Embed(
title=f"History of {member}",
description=
f"Choose the type of history you would like to view!",
color=discord.Color.purple())
await ctx.channel.send(embed=embed, view=view)
await ctx.message.delete()
await view.wait()``` The embed.
nvm ill just ask somewhere else
await ctx.channel.send(embed=embed, view=view)?
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
What do you mean "a mistake"?



