#discord-bots
1 messages Β· Page 787 of 1
import life as pytho-
but my system is easier, all I have to do is this and I have working slash commands:
slash_int.BotClient.CLIENT = client
slash_int.BotClient.TOKEN = TOKEN
slash_int.BotClient.VERBOSE = True
slash_int.BotClient.AUTO_UPDATE_GUILDS = True
slash_int.BotClient.RATE_LIMIT_MODE = 1
slash_int.BotClient.DEFER_AFTER = 1.5
import python as c#
and the last 4 lines are all unnecessary settings
I mean
the downside is i can only play with the new toys for slash commands
so I cant add menus and buttons when responding to messages
why even make a third party lib for slash commands that any fork has
btw u guys know the diffrence between bot.command and client.event?
and being bored
bot = disnake.Bot()
@bot.slash_command()
async def ping(inter: disnake.CommandInteraction):
"""Pongs your Ping!"""
await inter.response.send_message("Pong!")
bot.run(<token>)
```and you have working slash commands
yeah ill defs need to check out disnake
iirc nextcord syntax is very similar though
im not scanning 20k lines of code for bugs tho
so its either drop in or nothing lol
Im just a hobby programmer, danny come back 

somehow most of my bot's code isn't tied to any specific fork so I could probably jump ship in <30 minutes
danny wont
which is also the only reason I'm considering migrating to hikari
yeah
I mean again, I am enjoying my own solution to this, it just sucks I cant use it for normal message commands
thats why I was wondering if there is a 100% drop in
Hi, 'Im a beginner, and I wanted to add a "daily" command to a bot using mongoDB as a database
Here is what I have:
cluster = pymongo.MongoClient("the url")
db = cluster["UserData_db"]
coll = db["UserData_coll"]
@client.command()
@commands.cooldown(1, 60*60*24, commands.BucketType.user)
async def daily(ctx):
daily_earn = randint(20,30)
await ctx.send(f"Here is your daily income, **{daily_earn}**")
await coll.uptade_one({"_id": ctx.author.id}, {"$inc": {"money": +daily_earn}})
But when I execxute the command on discord there is this error :
Command raised an exception: TypeError: 'Collection' object is not callable. If you meant to call the 'uptade_one' method on a 'Collection' object it is
failing because no such method exists.
I don't know if I should post this here or in #databases
@slate swan :white_check_mark: Your eval job has completed with return code 0.
9
@slate swan :white_check_mark: Your eval job has completed with return code 0.
6
lines or letters?
yes
it clearly shows
so you're trying to make a max line rule
no \n is a built in to make a new line
dont you have to calculate how much letters the msg has and split them to know how many new lines theres in a msg since discord has a max line when you hit a max chars in a line
String.count("\n") would give you the number of new lines, including any blank lines
Yes it does return new lines. I'm not sure what you're talking about
message.content doesnt return \n
doesnt discord have a max chars then it makes a new line so why not calculate the amount of chars and split it to know the amount of lines
or is there a better way?
No
Yea
I still don't get what you mean. The new lines are absolutely returned in the content..If you're instead talking about wrapping lines then you should be clearer about that
?
Clearly not when someone is denying the existence of new lines in message content. But I think they are talking about wrapping
like i said divide the amount of characters?
No dude
does message.content even return \n?
I showed you earlier
let me check real quick
will return 4 since there is also the block quotes
Lmao
ill try it
yes ofc where the heck am i gonna pull the inspect element
Before it was possible
print(message.content.count("\n"))
ic
thats cool
can you send the whole payload or is that all?
lol
thank you lol
you made me learn how payloads look in discord
later lol
They are just JSON dicts that are sent to the API...
ik
i just didnt know what it had in it
i just didnt know how the response looks like bruh
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
!d discord.Guild.get_thread
get_thread(thread_id, /)```
Returns a thread with the given ID.
New in version 2.0.
seems cool
hwo to do i make the bot deletes its own message
pls osmeone help
ctx preferally
await ctx.message.delete()
thats user input
not bot deleting own message
examlpe
$dog
asdasd <- delete this message from bot
next mesaseg
ποΈ ποΈ
cant you do it directly and just use the delete_after kwarg
Not like that π
disnake git examplesπ³
ok how would u do it
Ask someone else now ,I gtg 
max you shouldnt be ignoring your cat brother
okay can anyone tell me why clonechannel command dont move channel to the place where it was before?
it just doesn't
but it do move back to place for galaxies bot, why it dont for me?
hey guys i want to make a /clear command for my bot, im having some trouble with the check= attribute of the .purge() function, can i have some help?
What is galaxies bot?
random verified modeartion bot
iguess but that doesnt matter.
i just need to know how to fix it
Because the programmer coded it to
Clone isn't meant to move the channel, just like when you do it manually. You need to manually (code) it to do so
@client.command()
async def unban(ctx,*,member):
banned_user = await ctx.guild.bans()
member_name, member_disc = member.split("#")
for ban_entry in banned_user:
user = ban_entry.user
if(user.name , user.discriminator) == (member_name,member_disc):
await ctx.guild.unban(user)
await ctx.send(f"unban {user.mention}#{user.discriminator}")
link = await ctx.channel.create_invite(max_use = 2)
await ctx.send("invite sent")
await member.send(link)
Can someone tell me how to make a function where if u unban someone it sends an invite link to them through a bot
you can't, unless the bot is in another server in which that person is as well
You cant send an invite link using just username and tag?
hello @slate swan, what are you doing?
i am trying to run bot on a vps
send the code
troling
You need to provide more code
please respect the channel topics and use english to the best of your ability as per our #rules . thank you
from distutils import command
import discord, os, json
from discord.ext import commands
from discord.ext.commands import CommandNotFound, CommandInvokeError
import datetime as datetime
from discord_components import (DiscordComponents, Button, ButtonStyle, Select, SelectOption)
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
client = commands.Bot(command_prefix='=', intents=intents)
client.remove_command('help')
@client.event
async def on_ready():
DiscordComponents(client)
print(f'Launched: {client.user.name} // {client.user.id}')
await client.change_presence(activity=discord.Game(name=f'Soporte de GamaLifeRP'))
i can run in my pc but in vps nope
You need to provide more code
!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.
The error must be on the line above, show the relevant code
@slim ibex anyway i can message you?
for?
about your rogue project
uhh ok
your dms are closed
added
Why are you importing datetime as datetime
Mans invented pep9
lmfao
I have this code for an application command, but sometimes it doesn't wait for the message so it will send an error
https://paste.pythondiscord.com/xojukehiji.csharp
The error would be that one of the values is empty
For the embed
Can you just send the part thst isnt working
Idk what part isn't working cause sometimes it works sometimes it doesn't
Ss the error
One sec
Ignoring exception in command apply:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 832, in apply
await channel.send(embed=emb3)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/opt/virtualenvs/python3/lib/python3.8/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 embed.fields.1.value: This field is required
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.1.value: This field is required
There is way too much code, you could just put adding fields into a loop @dire folio
there are too many useless embeds ngl
wym lock?
Itβ s cus you have soo much code you could easily put in a loop
the second field value of the embed is invalid
>>> import discord
>>> from discord.ext import commands
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
is there something wrong with this code? it aint supposed to error out, i got pycord installed
so, question, I was able to fully setup the bot on a fresh Fedora 35 pc
able to install all the requirements and dependencies
using python 3.10
when I lunch the bot I receive this error I've never seen 
You generate 10 or more embeds manually, if anything goes wrong it will all collapse
I'll try a loop
U need perms
await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the thread.
Editing the thread requires [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_threads "discord.Permissions.manage_threads"). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_threads "discord.Permissions.manage_threads") can unarchive a thread.
The thread must be unarchived to be edited.
U may need community or something, idfk
anyone
Or channel needs to be set up properly
Sure then (to your question in the DMs)
Check if everything is alr with ur virtual environment
there aint one
hmm
Not having a venv is a whole other issue
Using pycord is a whole other issue
nice
Lmfao
How would I put the previous answer into the value for the question
Whenever am here, why is there always either sarcasm or RPing going on
It's your aura
Ig this channel is just special
Because so many developers who create discord bots are new to programming
That's my guess
Ig
Elaborate?
Iβ m guessing Itβ s the first thing they jump into after learning variables and if statements
Yeah that's what I meant
They're so new they don't know anything
So you have to hold their hand through everything
Why bother with learning oop if u can just jump into asynchronous programming
I mean like in the previous code I sent, after answering a question the next embed would change (Enter your answer below) into your answer
Why bother learning python if you can just make a discord bot
Just have it in ram and change it in every iteration
Lmfao
π
How would I do that?
async def addxp(self, message, amount, user: commands.Greedy[discord.Member]):
members = user or [message.author]
if isinstance(lvl, int):
for k in members:
for i in range(len(info)):
member = k
user_id = robloxpy.User.External.GetID(str(member.display_name))
#check if info[i][0] is nonexistent
try:
info[i][0]
except IndexError:
print("IndexError")
message.send("You have reached the max RANK! NICE")
if info[i][0] in [role.name for role in member.roles]:
if i != lvl:
await member.remove_roles(discord.utils.get(member.guild.roles, name=info[i][0]))
if i == lvl:
await member.add_roles(discord.utils.get(member.guild.roles, name=info[i][0]))
Not giving or take role when u are not author
How do you store something in ram
No clue
variable = "Hi"
Now variable is stored in RAM with the value Hi
Variables are for making text command smaller
Bc code will look chunky without variables
For example if I was to print a paragraph I would use a variable
I think he knows what a variable is...
O lmao
I infact do know what one is
But I still have no idea how I would change the value @cedar stream
I got the easy bit which is the questions
u just redefine it...?
You store the answer in ram, you use it, when he answers new question u either replace old one or create new variable, depending on ur use case
!e
a = "letter"
a = "not a number"
print(a)
@quick gust :white_check_mark: Your eval job has completed with return code 0.
not a number
bruh thats basic python. if u dont even know how to change the value of a variable why do u even try discord.py
Obviously ik how to redefine a variable
mhm
I think I am not understanding your question then
ye lol
this is what i have
for item in h_list:
emb.add_field(name=item, value='(Enter your answer below.)')
await channel.send(embed=emb)
msg = await client.wait_for('message', check=check)
how would i change the value now
Which value
the embed
@dire folio u seem to me like u dont know python
sorry but it's just not adding up in my head
Hey, so I need help with something. I have Pycord 2.0, and there is almost zero documentation for dropdowns (Selects) online. When I select something from the dropdown, the message changes (the callback works), but the selected option in the view itself doesn't.
# Imports
import discord
from discord import SelectOption
# Dropdowns
class HelpDropdown(discord.ui.Select):
def __init__(self):
super().__init__(
options=[
SelectOption(label="General", default=True),
SelectOption(label="Economy"),
SelectOption(label="Games"),
SelectOption(label="Mail"),
],
min_values=1,
max_values=1
)
async def callback(self, interaction):
if self.values[0] == "General":
description = "**!help** :ArrowDown: \nShows this message."
elif self.values[0] == "Economy":
description = "Coming soon!"
elif self.values[0] == "Games":
description = "Coming soon!"
elif self.values[0] == "Mail":
description = "Coming soon!"
embed = discord.Embed(description=description, colour=discord.Colour.blue())
embed.set_footer(text="Do \"!help <command>\" to learn more about a command.")
await interaction.response.edit_message(embed=embed)
go to the interactions.py server
i think
Is it a help server for Pycord, or a help server for their own wrapper?
when u say pycord u mean discord.py?
well i dont really remember how to use pycord cuz the last time i used interactions was when discord components still existed
Just don't use pycord, simple
Any suggestions?
Is it basically like another maintained version of Discord.py?
Because I don't want to rewrite my entire code.
π
It's a fork
Just refactor discord to disnake and you're off to the races
However, is there an easier way to solve this problem?
Not me
I noticed
how do i make it so that any channel that starts with verify
it sends the embeds only once
kk thanks in advanced
How can I learn .py quickly?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
async def on_message(message):
if len(message.attachement) > 0 :
await message.channel.send(content=message.attachments[0].url)```why is this not working?
no such thing as quickly
πΏ
depends on how fast you learn how much time you have how much passion you have and overall you cant learn it quickly since theres so much to learn
what library are you guys using to make bots after discord.py got discontinued?
Disnake
!pypi disnake
whats the difference between disnake and pycord and etc
okay aight ill just trust u
Why are you pinging me
So umm........I'm just rewriting my bot and now I'm not able to trigger events that are in cogs ;-;
kk
Channel should be defined
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yes but its not good
!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.
Put the code in here
kkkk
PoV: You never loaded the cog
Pastebin fucks with formatting
if len(msg) > 30:
em = discord.Embed(title=" Welcomer Error!", description=f"You can't go over 30 seconds!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
Confirm the cog is being loaded
why is this not checking?
naise
This was the case?
if it isnt getting loaded, the commands shouldnt be loaded too?
yea
no? I'm not "that" dumb
my slash cmds are working, events are dying
I mean, its a common mistake many people can do
if len(msg) > 30:
em = discord.Embed(title=" Welcomer Error!", description=f"You can't go over 30 seconds!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
did u forget () after commands.Cog.listener?
no lol, they started working after I restarted for the 7th time
Β―_(γ)_/Β―
Well it's commands.Context not Contexts and run your code to see if you get an error
Maybe I'm missing something but channel should be defined
It's commands.Context not Contexts
if len(msg) > 30:
em = discord.Embed(title=" Welcomer Error!", description=f"You can't go over 30 seconds!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
if welcome_db is not None:
sql = (f"UPDATE welcome SET autodel = ? WHERE guild_id = ?")
val = (msg, ctx.guild.id)
if len(msg) > 30:
em = discord.Embed(title=" Welcomer Error!", description=f"You can't go over 30 seconds!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
em = discord.Embed(title=" Welcomer Successful!", description=f"Auto Delete has been set!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
cursor.execute(sql, val)
db.commit()
cursor.close()
db.close()
thats what i did
hellooooo???
Hi
can i get some help w that?
?
When you're running the command you need to include channel
mention a channel
where
[prefix]command #channel
When you're running the command
What?
????
ok and?
i cant put 1 channel
Then add *, before channel in your function arguments
I'm not sure how to describe what it does
What

π
I already told you. You need to pass in channel when you're running the command
What
i put it there
Put what in there
channel
Okay?
You made channel a required argument
When you run the command you need to add an argument for channel
kk
wait
wat
thats not what i wanted
Then change your code
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
How do I get the isinstance?
how do i make it so that when the embed is sent it looks for text
Trying to kick the bot or higher members
and if that text == something then it sends something
theres 3 embeds
in one command
One sec lemme remember that
commands.MissingPermissions?
does not work
!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
It should
discord.ext.commands.errors.CommandInvokeError
Can we see how you're trying to do it?
@kick.error
async def kick_error(self, error, ctx):
if isinstance(error, commands.MissingPermissions):
em0 = discord.Embed(title=f":no_entry: Error",
description=f"You do not have the required permissions.",
color=col_error)
await ctx.reply(embed=em0, mention_author=False)
if isinstance(error, commands.CommandInvokeError):
em1 = discord.Embed(title=f":no_entry: Error",
description=f"You can't kick that member.",
color=col_error)
await ctx.reply(embed=em1, mention_author=False)
exception discord.ext.commands.CommandInvokeError(e)```
Exception raised when the command being invoked raised an exception.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
So what about it doesn't work?
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
It's still sending in console?
Yess
@slate swan sorry couldn't find it
It has the special attribute for unwrapping
I don't remember it however
Are you sure it's from the kick command?
it is
your missing perms
!d discord.ext.commands.CommandInvokeError.original
i use cogs and i only have kick loaded
The original exception that was raised. You can also get this via the __cause__ attribute.
"Unwraps" to get the actual error
403 errors raise when you dont have permission to do such a request
All the errors are just wrapped with CommandInvokeError
ποΈ ποΈ
nice
sure
well youll have to add the kwargs in the super init
so the prefix and other kwargs
you cannot do such a thing
class Application(Bot):
def __init__(self):
super().__init__(command_prefix="")β
example
@slate swan found it
error = getattr(error, 'original', error)```
You need to unwrap the HTTP exception I believe
what people do is they run a method which runs the bot in another file and not an instance
wdym?
I just gonna use else xD
how would i use the same json file for 2 different bots in 2 different folders
Ok sure
Absolute path is a thing isn't it
just add a prefix and use slash commands?
There can't be more errors
Not recommended tho
what ever i do
yes it is
adding the prefix and just add slash commands?
thats what im saying????
yes but idk how to do that in this format ```py
with open("mainbank.json","w") as f:
users = json.dump(users, f)
!d disnake.ext.commands.slash_command ?
@disnake.ext.commands.slash_command(*, name=None, description=None, options=None, default_permission=True, guild_ids=None, connectors=None, auto_sync=True, **kwargs)```
A decorator that builds a slash command.
i am you add a random prefix and add slash commands?
why did disnake put slash commands into the commands extension
slash commands are native
Just put an absolute path to mainbank.json
im not even sure
all the way from the drive letter or how would i do that on a server
I also asked them and I don't really remember what they answer (it was a weird answer iirc idk)
On a server just copy the absolute path for the file
just check the python bot they use that method
like check the bot file and the main file
lol
@slate swan are you a beginner in bot development
no it doesnt?
your using the class to run a method inside it in another file which the run method had the dpy run to run the bot?
I had a stroke reading this lmao
not sure i dont do it like that
@slate swan I don't quite understand what are you trying to do, but it really seems like you are trying to implement the cogs and extensions in a weird way sorry if I am wrong tho
not ctrl c and ctrl v use it for guidance
no hes trying to subclass bot
but hes not sure how to run the bot

Superclass has run method
Put the super().run() into the end of the overwritten method
yes so you do
BotSubclass().run()
which the run method has the dpy run method
It inherits from superclass
a run method from the class that inherits the run method to run the bot
Btw what is this thing
bot caeden made with other devs that are generals here
I actually got invited to the development of this but when I saw AI and IDE I decided not to get in as I don't know a lot about that
nah its not hard because you get assigned to do something specific
i got kicked for no reason lol
hold up
Left that server cause someone in there can't remember who was acting kinda douchey ποΈ ποΈ
βΒ Β Β Β βdefβΒ βrunβ(βselfβ)Β β->βΒ βNoneβ:
βΒ Β Β Β Β Β Β Β βselfβ.βsetupβ()
βΒ Β Β Β Β Β Β Β βsuperβ().βrunβ(βTOKENβ,Β βreconnectβ=βTrueβ)
and you run the method
was caeden wasnt it
no
Dude with a picture of a goat or something as their pfp iirc?
oh him
that server is kinda toxic
bot file != main file
you run the bot in the main and the bot file is the subclass
That's about bot files hierarchy 
cogs
how do i wait for something in message
how do I kill a background task?
and if its not that it will send invalid
help my command did't work on Visual Studio its say command not found
but if i try on replit, its work, what wrong in my visual studio code?
@bot.command()
@commands.has_permissions(administrator=True)
async def test(ctx):
await ctx.send("test")
you make a setup function with a for loop which loads all cogs in a cogs folder and you run the setup function in the run method
!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**...
!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.
show the code
bot wait for
message in context
no such thing
context is the context of a command
i meant context
as the word
not the python thing
then what do you want?
ok
example
if the message CONTAINS
if 'dog' in message.content```
What for do you need the keep_alive
prob keep alive since i see nothing run with it
@slate swan see check param of the wait_for in docs also please look at the examples in there
?tag wait_for
This is not a Modmail thread.
no you use the wait for and make a function and you use the check kwarg
its just for Flask ignore it i forget to delete it
!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**...
kinda confused
@coral vessel alright there are no visible issues with your code, but do you get any errors?
make a function and do what you want the check and you put the function in the check kwarg?
the connection sure
..how exactly
hey folks sorry
is it possible to start a background task and then kill that same task later
Seriously i only get Command not found (no error)
Why not figure it out by yourself? We can give you code of course but it won't teach you anything
what if u send the code and explain
π§
So the bot runs?
await bot.wait_for('message', check=lambda m: m.author.id==ctx.author.id)
if irrc
example btw
@vale wing does it need if im not sure
Shouldn't it be 'on_message' not just message?
nope
It doesn't
yeah i thought so
That's da lambda function π₯΅
yes sir
@vale wing on wait for events are like that
'on_raw_reaction'
would be
'raw_reaction'
No, you leave out the on_ prefix for wait_for()
hey π i'm good, you?
Mmmm discord.py's on_ stuff is pretty annoying
yeah not sure why they do it since the gateway just gives you events like MESSAGE_CREATE
betterπ π³
Yea and plus all the events are string literals in discord.py
So you don't get auto suggestions from your IDE
Shameless plug but rin uses enums π
wuts that
@slate swan so basically the function you parse to check accepts an argument depending on your event, in this case it will accept single argument Message. Then the function just returns whether the message matches your needs or not. If it does, the event waiter stops, if not it continues to wait for the event to make the check function return True
@GatewayClient.on(rin.Events.MESSAGE_CREATE)
Thx kinda forgot about that
create events are events from the gateway for the bot to cache it right
Uhhh yes, if I understood you correctly
yes, bot run, without error, i just can't call command its said "Command not found"
if running on VS Code, but its running well and command work with Replit.
i want message contains
nooo just message like the event youre waiting for
The first arg of wait_for is an event not a link
yes
just the gateway says to the bot yo theirs a msg cache it
but i want it to be that
How do you run the command?
go to vc 1
Close, the gateway says there is a new thing created, the library wants to cache it though
ah ic thanks
why is my mic suppressed
Caching is a library abstraction
?????
But it's best to cache anyways
by?
It would be stupid to not do so
Wdym by
The API doesn't tell the client to cache
It's a design choice to cache things
like this
A good design choice
then what does
broπ³
ποΈ ποΈ
so like this? py with open("/home/maskuh/discord/discord bot\mainbank.json","w") as f: users = json.dump(users, f)
@pliant gulch so gateway sends a msg and the bot has a message create event and it caches it?
wait no
bots dont cache msgs
A message is sent > Gateway dispatches MESSAGE_CREATE > wrapper says oooh we got a new message. Let's shove this into the cache
ic but doesnt bot not cache msgs or im just confused with something else
The wrapper puts the message into the bot's cache
Or somewhere else
In my old wrapper the cache was inside of the bot
Now the cache is inside of the object itself
E.g bot.messages vs rin.Message.cache
so bots do cache msgs?
do it does cache it but the bot doesnt have access to it?
bro
π³
the Gateway only SAYS a message got created and sends back the message data
yes
It's UP to the WRAPPER/LIBRARY to cache it
yes
E.g the maintainers of said wrapper/library decide to make code that caches
The API by itself does not provide caching
ik
I'm so confused by what you asking
I guess so
im confused myself on what i asked
Your last question on whether or not the bot has access to the cache is dependent on the wrapper. It makes sense that the bot has access but there is always a case where someone decides not to
nah nvm i just got confused with many things i have in my head
It could be given internally, or publically
Up to the maintainers/contributors
ok i'll try it
yeah
sorry for the dumb question i just confuse myself allot 
i get it now thx
You could decorate that function with commands.Cog.listener and just add the cog with it to the bot
or just add it to the subclass which i like better
There may be a way to register an event listener but this is how you typically do that - cog or overwrite in the subcalss
show
no no no
just on ready dont do self.run it will never work
ok make it mesage contains
and make it work
pllsssssssssssssssssssssss
Why are you running it from a running bot 
^
you run the run method in another file which is the main file
When it logins and connects
Isn't Application a subclass of commands.Bot already? Why are you subclassing the subclass again
error: code: https://paste.pythondiscord.com/ufocolutin.py
already test it with prefix, but still command not found, i think it VS code issue, cause my code work with Replit, did anyone know how to restore/reset default VS code without uninstalling?
You should just do ```py
bot = Application(...)
bot.run(...)
Whatever your doing makes no sense
bot.run() launches the asynchronous app which means none of the functions after it will be executed until the loop is closed, just for your info
hes trying to subclass bot andy
like anything else?
Inside of your subclass, E.g Application you add a method called on_ready
You give it the self param then now it's set as a listener implicitly
Check the version of your dpy
make sure you indent the stuff you want to put under your __init__, lines 15-25.
You only need to subclass the bot when your adding something new, an API for doing things in another file exist already, E.g Cogs
i did
If you're still getting that error, you didn't indent it enough
@slate swan
from bot import BotSubclass
if "__name__" == "__main__":
BotSubclass().run()
is how you run the bot which will just run the run method in the subclass which the run method runs the bot and the setup function to load all cogs and then just add the on_ready event below
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
You'd use this the same way you'd use bot.event etc
Except keep in mind the methods will be bound to your cog class
thus you need to give self in the method's signature
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html Please read this
now it can't find the embeds now that i indented it same code just tabbed once more
did you mean for begEM to be a self variable?>
it is not but i could
@slate swan you can check this out as well https://tutorial.vcokltfre.dev/tutorial/05-cogs/
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
like this or
Have you even read the manual I sent you before asking that question
@slate swan maybe check this?
class Gambling(commands.Cog):
def __init__(self, bot):
self.bot = bot
``` this is shown in the example
ποΈ ποΈ as you can see it get's bot
does anyone here know how to use fuzzywuzzy
Do you realize you need to actually construct the Cog later or use the setup method
Thus you'd be giving your INSTANCE to the cog
bot.add_cog(Greetings(bot))
ποΈ ποΈ
or use the setup method
For some odd reason not covered in the original docs, but vco's tutorial shows it
yeah thats just making an instance of the class and doing everything else
anyone?
how would i make something like this in my bot?
How can i mention a user my his username with a discord bot?
lol that is not how you make a cog
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
its called image manipulation
if you are using cogs make a listener
bro wut did you replied to the run msg?
@slate swan try this
from bot import Application
from disnake.ext.commands import Cog
bot = Application()
bot.run()
class Events(Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(self.bot.name, "is online")
bot.add_cog(Events(bot))```
yea i'm not new to cogs
why the heck is bot.run there
and no need for @commands.Cog
really
you imported the cog class
is there a way to ignore commands.errors.CommandNotFound?
i use that
not that i know of
just do Cog.listener
intresting
Catch it in an error handler and don't respond
No error will be printed to console
which dont
thx
then in the feature you wont know what error is happening
so how would i do it so it has the channel and a member mention?
like the photo
if your doing a expect
i sent
if not use on_command_error
If you're doing on_command_error you'll need to add a print statement within an else block at the end printing the exception
So it only catches the errors that you specify
Wait does this guild offers BetterDisco-py help?
on member join event takes a member obj use it and get the channel
It's for all relevant discord bot development libraries
resolved thank you pep8
i do this rn py @commands.Cog.listener() async def on_member_join(self, member: discord.member): if member.guild.id == 804864012184977438 : return if member.guild.id == 902404450432483378 : return channels = member.guild.channels for channel in channels: if ('welcome' in channel.name.lower()) or ('joins' in channel.name.lower()): #or ('testing' in channel.name) embed=discord.Embed(title=f"Welcome {member.name}", description=f"Thanks for joining {member.guild.name}!") embed.set_thumbnail(url=member.avatar_url) if isinstance(channel, discord.TextChannel): await channel.send(embed=embed)
Can I see how you did it?
Ok thank you
I want to make sure it doesn't cause you any issues in the future
yeah gimme a sec
from discord.ext.commands import CommandNotFound
@client.event
async def on_command_error(ctx, error):
if isinstance(error, CommandNotFound):
return
raise error```
So I tried using the command it does not recognize the command
What's the library called?
no need for return
raise returns a function and raises the error
BetterDisco-py
You sure?
!pypi Disco-py
why use it
This is the new one https://github.com/elderlabs/BetterDisco
Bom dia
@slate swan How would i make this look like this
??? google says Someone give me dreams please Dreams
image manipulation
only english pls
i've never done anything like that do you have an example?
!pypi pillow
how would i make it print the channels clickable and mention the user?
a command that does that?
property mention: str```
Returns a string that allows you to mention the member.
You can mention the member with this
And to mention the channel you would do <#channel id here>
that is real helpful
can you show me an example?
please
@final iron
member.mention()
He asked how to mention a user
Yea... and that's not how you mention a user
!e ```py
class A:
@property
def mention(self) -> str:
return "foo"
a = A()
a.mention()
No it's not
@pliant gulch :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | TypeError: 'str' object is not callable
I'm saying grab a member object and call its .mention() method lol
!d discord.User.mention
property mention: str```
Returns a string that allows you to mention the given user.
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
i quess i'll wait
No mention method
Where does it say it's a method??
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
support_channel = self.client.get_channel(
support_utils.get_support_channel_id())
alert_channel = self.client.get_channel(
support_utils.get_channel_alert_id())
if before.channel != support_channel and after.channel == support_channel:
embed = disnake.Embed(
title='A member has joined the support channel!',
description=f'{member.mention} has joined the support channel!',
color=0xFFFFFF
)
So this won't work?
Bro
In the snippet you sent you are USING it properly
You told him EARLIER to call IT
You're not calling it in that code
"member.mention()`
Oh fuck
that would thanks i used it like that in an embed
HAAHHAHAAHAH
π€¦
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
Also check out the nickname policy
@welcome.command(aliases=["msg"])
@commands.check_any(commands.is_owner(), is_guild_owner())
async def message(self, ctx, *, msg):
if msg == None:
em = discord.Embed(title=" Welcomer Error!", description=f"Please provide a message!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
with open(prefix_path, "r")as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)]
p = prefixes.get(str(ctx.guild.id))
query = "SELECT msg FROM welcome WHERE guild_id = ?"
val = (ctx.guild.id,)
with sqlite3.connect('./database.sqlite3') as db:
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute(query, val)
welcome_db = cursor.fetchone()
if welcome_db is None:
em = discord.Embed(title=" Welcomer Error!", description=f"First setup your welcome channel! `{p}Welcome Channel [Mention/ID]`!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
if welcome_db is not None:
sql = (f"UPDATE welcome SET msg = ? WHERE guild_id = ?")
val = (msg, ctx.guild.id)
if int(msg) > 2048:
em = discord.Embed(title=" Welcomer Error!", description=f"You can't go over `2048` characters!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
em = discord.Embed(title=" Welcomer Successful!", description=f"Welcome message has been set!", color=discord.Color.from_rgb(black1, black2, black3))
await ctx.reply(embed=em, mention_author=False)
Use len to get the length of a string
len(msg)
of the*
len can be used in many things lol
your grammar
your saying it like if it can only get the length of a string
ok then...

How to display the number of participants from all servers where the bot is located?
Does anyone has any bot idea? Or any project I can help with?
!d discord.ext.commands.Bot.get_all_members
for ... in get_all_members()```
Returns a generator with every [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") the client can see.
This is equivalent to:
```py
for guild in client.guilds:
for member in guild.members:
yield member
thanks you
yw
Question
await ctx.send(file=discord.File(r".\files\gme.png"))
this works on Windows but not on linux [as in, the bot is hosted on a linux machine] what should be changed?
try using forward slashes instead
"./files/gme.png"
should work on windows too
uhm... doesn't seem to like it 
How so?
Well that has nothing to do with your filepath
ah strange it told me only after I did those edits 
For a cog with on_message event, can I change βif message.author == bot.user:β to βif message.author == commands.userβ?
Or should I do smth else to make it
The cog should take bot as an arguement. You can assign it to self.bot and use it in ur event
Hi, I was wondering if there is a way to get the thumbnail on an embed to load/work before sending the embed
Wdym
when I send an embed, I am setting the thumbnail and it doesn't show up
Itβ s cus Itβ s not loaded on ur machine
so then how can I load it?
isn't there a way to get it to load before sending the embed?
No because every computer (my phone, your computer etc.) has to load the image for itself
nws
How did u implement it
I am using an api
f"https://www.accuweather.com/images/weathericons/{str(weather_data['DailyForecasts'][0]['Day']['Icon']).zfill(2)}.svg"
weather_embed = disnake.Embed(title=f"Weather", url=weather_data['Headline']['Link'])
weather_embed.set_thumbnail(url=f"https://www.accuweather.com/images/weathericons/{str(weather_data['DailyForecasts'][0]['Day']['Icon']).zfill(2)}.svg")
ok
ahh
<ClientResponse(https://www.accuweather.com/images/weathericons/04.svg) [403 Forbidden]>
<CIMultiDictProxy('Server': 'AkamaiGHost', 'Mime-Version': '1.0', 'Content-Type': 'text/html', 'Content-Length': '306', 'Cache-Control': 'max-age=0', 'Expires': 'Sat, 29 Jan 2022 23:02:01 GMT', 'Date': 'Sat, 29 Jan 2022 23:02:01 GMT', 'Connection': 'close', 'Server-Timing': 'cdn-cache; desc=HIT', 'Server-Timing': 'edge; dur=1', 'Strict-Transport-Security': 'max-age=15768000 ; includeSubDomains ; preload')>
the api needs a auth header
some apis need a auth token to verify a request to it
If you are scraping the image then you can just copy the token from inspector
Otherwise generate an api key
^
I don't have one xD
I found that if I copy image path I could get the icons, and I can fiddle with the file name to get the icon
the api is different, I have a key for that
not how you do a request in that api hut youre probably missing a auth toke since a 403 error was raised
Go to that url in browser and go to inspect element/network then look at which request responds with an image and make identical request
I am not gonna lie, I am pretty newbie when it comes to requests, I found some of my old code (which I am pretty sure I stole) and it works so I use it
async with ClientSession(headers=None) as session:
async with session.get(link) as response:
Yes but you need right headers
so, how would I pass proper headers?
You can see what headers u need in inspect element/network in ur browser
Go there and find the request that responds with the image
just check the api endpoint
And copy Itβ s headers
it will show the params
there is nothing here
Refresh
this is something else, the api uses a different link
Are u using an api or are you scraping
channel = bot.get_channel(699577970117050399)
messages = await channel.history(limit=500).flatten()
for p in messages:
print(p)``` this works but it prints the message id of all the messages instead of the content
Just do p.content
no it probably doesnt check its docs you will see the endpoint url with the params
Print(p.content)
I am not sure, I went to the website https://www.accuweather.com, found a location for weather, and there is an icon, so I copied image path and now here I am
I think p is an instance of discord.Message
messages is a list
I think he is scraping images off web
So no docs
Make the same request browser does to get that image
in that case yeah no docs
got it thanks
@cedar stream it works but it skips images
is their a way to print the image url
instead of where an image should be there is just empty space
Like in discord?
try print(p.content)
Idk wym
it works but it skips all the images
Ohhhh
those are attachments
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the messageβs hash.
my pfp is looking at the msg above
No, Itβ s looking at my pfp
it works thanks bro
trueποΈ ποΈ
No
what
ποΈ ποΈ
the typoπ
who did that π³
Horrible person