#discord-bots
1 messages · Page 1120 of 1
ye...
When starting the bot
@bot.event
async def on_ready():```
You need to get a specific guild then
From what specific guild do you want to get its members' IDs
And what do you need this for?
Some system?
Economy system. The bot must, at startup, iterate over all server members (id) and check the value in the database. If the value is None - the bot performs a specific action
main.py:17 RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(extension)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
help
You forgot to use await
@dusky pine check prs
Do this in a setup hook
I can not understand what you mean
I do it
Uhm i had a look at discord.py but the docs kinda suck. Isn’t there something in python with a better tutorial (like discord.js)?
help
await bot.load_extension(extension)
File "main.py", line 17
await bot.load_extension(extension)
^
IndentationError: unindent does not match any outer indentation level
u know what is indent right?
How did you mess up the indentation
Oh dude holy shit this is awesome
thats what im about to say
i'll review later
I?
sure
no
this
is
indent
!indent
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
dk why there's no command with the full name 💀
?
the command name is indent but as you can see in the title it should actually me indentation
oo lol
elif value == "Ban" or "B":
embed = discord.Embed(title="🔨 Ban", description="Służy do banowania użytkowników.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ban <@użytkownik> <powód>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ban @człowiek spam`')
embed.add_field(name="🗂 Kategoria:", value="Moderacja")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Banowanie członków")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Brak.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.b`")
await ctx.send(embed=embed)
elif value == "Ogłoś" or "Oglos" or "O":
embed = discord.Embed(title="📢 Ogłoś", description="Służy do wysyłania wiadomości na #📢-ogłoszenia.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ogłoś <ogłoszenie>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ogłoś coś tam ważnego`')
embed.add_field(name="🗂 Kategoria:", value="Ogłoszenia")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Zarządzanie kanałami")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Możesz pisać jakiej chcesz długości wiadomości póki nie będziesz miał/a limitu od discorda.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.oglos`, `.o`")
await ctx.send(embed=embed)
when i write .pomoc ogłoś bot send to me what it should be .pomoc ban
i don't have error
if __name__ == '__main__':
for extension in extensions:
await bot.load_extension(extension)
?
seems right
but you can't use await outside an async function
You shouldn't be loading extensions like this
consider using setup_hook 👀 or make a coroutine which loads the extensions and then uses bot.start
why did i write embed, idk
I am making the bot on replit.com
So what should I do?
There's a template with a cog or two set up
@slate swan
Use dicsord.ext.tasks.loop if you are using discord.py
@tasks.loop(seconds=15)
async def status_roles(ctx):
guild = client.get_guild(921366728016011324)
fluf = await bot.fetch_user('716707479005823036')
for member in guild.members:
if member.activities and 'discord=i' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'dis=oofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
elif value == "Ban" or "B":
embed = discord.Embed(title="🔨 Ban", description="Służy do banowania użytkowników.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ban <@użytkownik> <powód>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ban @człowiek spam`')
embed.add_field(name="🗂 Kategoria:", value="Moderacja")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Banowanie członków")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Brak.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.b`")
await ctx.send(embed=embed)
elif value == "Ogłoś" or "Oglos" or "O":
embed = discord.Embed(title="📢 Ogłoś", description="Służy do wysyłania wiadomości na #📢-ogłoszenia.", color=0xffffff)
embed.add_field(name="📕 Użycie:", value='`.ogłoś <ogłoszenie>`')
embed.add_field(name="📖 Przykład użycia:", value='`.ogłoś coś tam ważnego`')
embed.add_field(name="🗂 Kategoria:", value="Ogłoszenia")
embed.add_field(name="🚨 Potrzebna permisje:", value ="Zarządzanie kanałami")
embed.add_field(name="💾 Dodatkowe informacje:", value = "Możesz pisać jakiej chcesz długości wiadomości póki nie będziesz miał/a limitu od discorda.")
embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.oglos`, `.o`")
await ctx.send(embed=embed)
when i write .pomoc ogłoś bot send to me what it should be .pomoc ban
i don't have error
help @slate swan
!d discord.ext.tasks.loop use a task, use get_channel to get the channel, and use .send() method
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Hi, hi, just a simple question;
I'm working on my bot, and came to the idea to make an anti-raid prevention. So, first of all it is checking if the message has more then 1 character, and if it doesn't it does get deleted. But the problem here is, that It does also delete it, if someone only sends a picture as it doesn't contain any message in it. Now I'm just asking, how can I check if there's an attachment? I'm honestly for some reason not finding it out;
if len(msg.content) < 2:
if msg.content # I don't know for what I should check here
await msg.delete()
return await msg.channel.send(f"Hey {msg.author.mention} Your message can not contain less then 2 characters. This is an anti-raid prevention to keep the server clean.", delete_after=5.0)
!d if
8.1. The if statement
The if statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
``` It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section [Boolean operations](https://docs.python.org/3/reference/expressions.html#booleans) for the definition of true and false); then that suite is executed (and no other part of the [`if`](https://docs.python.org/3/reference/compound_stmts.html#if) statement is executed or evaluated). If all expressions are false, the suite of the [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) clause, if present, is executed.
fluf = await bot.fetch_user('716707479005823036')
the argument needs to be an integer
A message object should have an attachments property
oh
I'm aware of that, but I don't seem to find a solution
!d discord.Message.attachments
A list of attachments given to a message.
Oh, damn. I didn't thought it's that simple, thanks lmao
👍
still nothing
no error
no role given,no message
sidenote: this can raise an error if there's no content in the message ( im not totally sure tho)
If there is no error then the user was fetched or this line wasn't run
did you even start the loop
And yeah, tasks.loop loops need to be started
how-
@loop(...)
async def foo(): ...
foo.start()
``` since its a loop working with requests consider doing it after wait_until_ready
ooooooooooooooooooooooohhhhhhhhhhhhhhhhhh
why tf
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
did it 😏
Loop is the object which @loop constructs
Makes sense I guess
👀 its same for commands
@commands.command()
async def foo(ctx):
...
``` `foo` here will become a commands.Command object
Yeah they do do it like that
File "main.py", line 59, in status_roles
for member in guild.members:
AttributeError: 'NoneType' object has no attribute 'members'
help
property members```
A list of members that belong to this guild.
i did guild = bot.get_guild(921366728016011324)
then perhaps the guild I'd not there in cache
hoooooowwwwwwwwwwwwww do i put it in cache]
fetch_guild
guild = bot.get_guild(921366728016011324) or await bot.fetch_guild(id)
id here is the number please don't copy paste
oh
bot.fetch_guild
or await bot.fetch....
oops didn't read
ghow tf did you get that iphone sob emoji
nitro hax
:Sob:
still no error no message no role
hmm
people crying irl look better
💀
async def status_roles():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
for member in guild.members:
if member.activities and 'discord=loofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discordloofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
status_roles.start()
help
start that task after the bot is ready
oh
after bot.run?
@tasks.loop(...)
async def task(): ...
async def start_task():
await bot.wait_until_ready()
task.start()
async def on_ready():
await start_task()
something like this
wwwwwww
i did it
STILL NOT WORKING
@tasks.loop(seconds=10)
async def task():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
for member in guild.members:
if member.activities and 'discordoofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discoofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
async def start_task():
await bot.wait_until_ready()
task.start()
async def on_ready():
await start_task()
help
please
Won't that wait forever
Or does on_ready fire after the bot is ready
In that case doing await bot.wait_until_ready() is unnecessary
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Hm, it's triggered when the not connects to the ws
@tasks.loop(seconds=10)
async def task():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
for member in guild.members:
if member.activities and 'discordoofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discoofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
@task.before_loop():
async def pre():
await bot.wait_until_ready()
async def on_ready():
task.start()
Verify what member.activities[0].name.lower() is. It might be that the strings you are checking it with are/aren't there
just add a print statement and see if the task is starting
Also fetching the guild and the user every ten seconds spends an unnecessary amount of time
@task.before_loop()
TypeError: before_loop() missing 1 required positional argument: 'coro'
dont call it
Just remove the whole pre function definition thing and put await bot.wait_until_ready() in the function of the loop itself
I think that would be best
wdym
its still giving this error @task.before_loop()
TypeError: before_loop() missing 1 required positional argument: 'coro'
on_message has message, not ctx
and why are you even getting a channel
also, use @bot.listen() instead of @bot.event just here
@paper sluice @maiden fable
stop calling before_loop 😢
how much options can I have in an autocomplete?
add a print and check
print where
oh
its not printing anything 😦
we assume it doesn't work
guild = bot.fetch_guild(921366728016011324)
fluf = bot.fetch_user(716707479005823036)
@tasks.loop(seconds=10)
async def task():
print("hello")
for member in guild.members:
if member.activities and 'discordoofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discoofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
async def on_ready():
await bot.wait_until_ready()
task.start()
hekp
don't start it inside on_ready
above bot.run
okay
error
await self.coro(*args, **kwargs)
File "main.py", line 62, in task
for member in guild.members:
AttributeError: 'coroutine' object has no attribute 'members'
guild = bot.fetch_guild(921366728016011324)
you have to use await
await where?
await bot.fetch_guild
ooh
none of your if statements are true
you don't have one
I don't see it
i can't either
How can I avoid the webhook erroring like so after a certain amount of time? disnake.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token Context: I have a slash command and I edit the original message every so often, and after a while, it errors like so
noww?
\
Im making a discord bout with slash-commands and they work and all but I am making one that sends an embed so I make the embed perfect and then I do ```py
await ctx.send(embed=embed)
and the error is "unexpected keyword argument embed"
yes
@tasks.loop(seconds=15)
async def task():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
print("Function done")
for member in guild.members:
if member.activities and 'discoloofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discorloofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
keep_alive()
bot.wait_until_ready()
task.start()
bot.run(token)
still no role
nope, there are many cases where on_ready gets triggered and the cache is not filled up, thats the only reason why wait_until_ready exists
@tasks.loop(seconds=15)
async def task():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
print("Function done")
for member in guild.members:
print('h')
if member.activities and 'discordfi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discorloofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
!d discord.Client.wait_until_ready ensures that the cache is ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook "discord.Client.setup_hook") can lead to a deadlock.
its not printing h but its printing function done\
you don't have member intents
!intents read this and see the codeblock
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
How would I go around implementing a queue for commands so the command happens after the other has finished
still no h
show your commands.Bot variable
bot = commands.Bot(command_prefix="-", owner_id=716707479005823036, intents=intents)
from discord import Intents
from discord import Embed
os.system('clear')
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="-", owner_id=716707479005823036, intents=intents)
seems good, still no hs?
and did you use the method i asked you to?
not printing h
how do i do it then
you need presence intents, you could just use Intents.all()
and enable presence intents in the dev portal
yeah it should print h
if youre trying to share the full code snippet, please remove the guild invite url from it and try again. our filter doesn't like invite urls.
Guys is it possible to make a afk command without database?
@tasks.loop(seconds=15)
async def task():
guild = await bot.fetch_guild(921366728016011324)
fluf = await bot.fetch_user(716707479005823036)
print("Function done")
for member in guild.members:
print('h')
if member.activities and 'discord=oofi' in member.activities[0].name.lower():
await member.add_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'gave supporter role to {member}')
elif member.activities and 'discor=floofi' not in member.activities[0].name.lower():
await member.remove_role(discord.Object(id=921720262217568268))
await DMChannel.send(fluf, f'removed supporter role from {member}')
keep_alive()
bot.wait_until_ready()
task.start()
bot.run(token)
help
please
yes but it will reset as soon as your bot restarts
someone
please
is it because my server has 400+ members
and it takes time to go through all of them
no that should not be the case
it should print h when checking every member
and looping on 400 elements shouldn't take too much time either
hm
what's the formatting for having thats ascii box in an embed which works on phone as well like 3*` followed by __
does it need to be Member instead of member
or members
How can I avoid the webhook erroring like so after a certain amount of time? disnake.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token Context: I have a slash command and I edit the original message every so often, and after a while, it errors like so. I am not too sure if it's the command interaction timing out or something or whatever, but I'm so so so lost
You can only edit the original message once I believe
I was able to edit it multiple times
but maybe there is a limit...
never thought of that
here, this might help ```py
async def slash_command(self, inter: disnake.CommandInteraction):
await inter.response.defer(ephemeral=True)
while 1:
await inter.edit_original_message(...)
async def waifu(ctx):
try:
async with aiohttp.ClientSession() as session:
async with session.get("https://nekos.life/api/v2/img/waifu") as r:
data = await r.json()
await ctx.send(data["url"])
except Exception as e:
await ctx.send(f'{e}')
``` why isnt this working? it just send in the chat *storage_url*
😅
i gave up
why do you have wait_until_ready there
@tasks.loop(seconds=15)
async def task():
await bot.wait_until_ready()
guild = await bot.get_guild(921366728016011324)
fluf = await bot.get_user(716707479005823036)
print("Function done")
for member in guild.members:
print('h')
if member.activities and 'discord=oofi' in member.activities[0].name.lower():
await member.add_roles(discord.Object(id=921720262217568268))
await fluf.send(f'gave supporter role to {member}')
elif member.activities and 'discor=floofi' not in member.activities[0].name.lower():
await member.remove_roles(discord.Object(id=921720262217568268))
await fluf.send(f'removed supporter role from {member}')
keep_alive()
task.start()
bot.run(token)
not sure about the discord.Object way there
you have to use the wait_until_ready method at the top inside the task function
nvm
- after being ready you can get items from the cache with
get_instead offetch_
dont ever do that
oh, how come?
you shouldnt run an infinite loop for edit_original_message
and you are probably running out of number of edits
OH, there is a limit
what
see what meh did
you got any ideas on how I could change it, should I just delete the message and send a new one or?
why would you want to run infinite edits?
Help
i am gonna cry😭
Im making a discord bot that can lookup "Ip Addresses" and Im making it use / commands and use embeds but when I try used embeds it does an error even though its perfect this is the code for the end embed
await ctx.send(embed=em)
what's the limit👀
it's a thing to keep tracking the spotify songs on a discord activity, and after 15min of no new songs, it lists all the song you have listened to
who knows
lel
what's the error?
TypeError: send() got an unexpected keyword argument 'embed'
idk i used it in the button map Walker with defer and it seems to work even after lot of edits
full error please
cant
but did you have it in an infinite loop
nice then help yourself
hmm no
i had it in just the callback
how much options can I have in an autocomplete?
if there is callback why make a loop
25
dont use a third party library, v2 supports inbuilt slash commands
Im using repl
....
I cant use v2
why is that?
I tried
please elaborate with reasons
and wont work
I tried it and it didnt work
umm, I think there's a way like if user types other options will be searched
how can I use that?
only 25 possible
discord always allows 25 cap buttons reactions options
but I've seen a bot which have that search one
nice, good luck getting help
i took a look in the help channel then went to clean my eyes with kleenex
yeah u can search from only 25
it is having more then 25, probably upto 900
why not make a custom function using fuzzy wuzzy or difflib for that
what's that?
pft
that is a pokemon information bot
bro i mean i know almost 0 to none abt slash commands and that still didn't make sense to me
then use fuzzy wuzzy or difflib
It's 2022 and you're om the internet, what do you want to make sense anymore?
🤦
wait a min
true
!pip fuzzywuzzy
its inbuilt
f difflib is in built
!d difflib
yeah
Source code: Lib/difflib.py
This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.
!pip discord-py-interactions
install 2.0 using pip once the poetry file is built
use the 2.0 git link
do you guys have any command ideas?(for beginners)
make an anime wrapper
won't it work for me?
lemme look at the docs wait a sec
make a waifu command
already did
ic
husbando command then
^
okay
A good bot base that is easily expandable.
how many options can we have for auto complete in slash commands
See pydis/botcore for ideas
akg ^
When we create a new bot we always use that core
webhook = await message.channel.create_webhook(name=message.author.display_name)
await webhook.send(content=message.content, avatar_url=member.display_avatar.url)
i have this code to create a webhook and send message, but the bot does not create webhook and i dont get any traceback/error
some1 know whats wrong?
Make sure you have a strong foundational infrastructure before making commands
is there like a good gist or docs on how to do that
But by using [...][:25] you can use a broader suggestions.
Not that I know of. It goes more or less unnoticed as people make guides on more interesting things
ic hmm
How can you have me a idea?
a dictionary
that's what I'm looking for
I know 😉
afk={guildid:{userid:message}}
any examples or docs for it?
Just my big brain.

!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.
Example:
I use disnake
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
so I just need my options in that list and it is enough?
Basically any iterable that only contains strings yes.
And max a list of 20 options.
u can use fuzzy wuzzy or difflib to narrow down and then do [:25] in place of fruits list ig not too sure
I have 118
^ this should work then right panda?
You don't need any fuzzy or wuzzy since Discord does that for you.
he has more than 20 initial options tho
so just pass the list of strings?
I know but you only need the [:20] really
If you want certain items to be on top you'd need to manipulate the list but else it will just be alphabetically.
so he has a list of Pokemon names i assume and since he wants to auto complete then if he just uses first 20 it won't work

he needs to narrow it down to around 20 options and then pass as options right?
Hence the [:20]
yes
!e print(list(range(100))[:25])
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
so for the narrowing down i suggested difflib or fuzzy
ik that
No he doesn't need that since Discord does that for you, it's the same as the Discord search bar in guilds.
ic
And the default of that is fuzzy matching.
!e py options = ["option 1", "option 2", "option 3", "option 4"] print(options[:3])
@honest shoal :white_check_mark: Your eval job has completed with return code 0.
['option 1', 'option 2', 'option 3']
so discord sorts that list and then u just pick 20 using [:20]
For really basic stuff yes, you can also apply your own fuzzy on the list if you really want that but from personal experience it's fine.
ic i haven't used slash b4 so wasn't familiar with the procedure
Slash has it's good sides.
I use it because it has strict datatypes so you don't have to keep in mind that people are annoying.
why... should i delete it?
I think the dynamic autocomplete is one of the better features of slash commands, I was able to fetch records from my database and feed it through
Don't forget choice as well.
Is this fine?```py
ok = ["xyz", "zyx", "yxz", ...]
@bot.slash_command()
async def abc(inter: disnake.CommandInteraction, options: str):
...
@options.autocomplete("ok")
async def ok_autocomp(inter: disnake.CommandInteraction, string: str):
string = string.lower()
return [opt for lang[:20] in ok if string in opt.lower()]```
I was debating that with myself. Wasn’t really sure of the difference
Well with autocomplete you can also input your own custom string and choice forces you to choose.
choices aren't dynamic either afaik
Very true.
Should I make one bot with many functions or should I divide the functions into multiple bots? Don't know if it matters at all
Depends on the "functions".
delete what? (I cant see the message that was replied to)
Regarding him installing dpy directly from git
Guys is there any cloud database that i am use in my discord bot for prefixes for free
And it can be used on replit
replit allows the usage of sqlite
But i am a mobile user
hm ic thanks
Do it matter?
Coding on a phone..?

And sqlite not work on mobile
@slate swan
give me one good reason why
It's a service from replit lol it has nothing to do with your phone.
You mean replit db?
no sqlite
Replit also have it's own db but bad one
it is not okay since you should be installing it using pip and simply downloading the files will only make it accessible at that specific path where the folder is located
nobody told you to use that? ps it has a limit to 1 gb of data only
I want to use of prefixes
I'd suggest to save the hassle and use the repl it db
coding on phone must be awful
no
replit db isnt that good
plus it's not async like aiosqlite
and you can only have 1gb storage per repl iirc
but i set the package path to Python39\Lib\site-packages
its okay? or should i delete and reinstall using pip?
its json but worse
why arent you using pip in the first place....
I know, God
its giving me error when i use git+https
gawd
install git first
^
thx xd <33
So what would you recommend me ?
@slate swan
but should i keep the package or delete it and reinstall it using pip?
There is an async driver for it, (in the official repo) And it's 50 MB per database
delete
ic that surely is weird
yo andy, how do u quit the terminal when u do :sp | terminal
postgreSQL but if the bot isnt really gonna be that big, I'd suggest sqlite
My bot is of 50 mb
Will it work on replit?
yes?
as in popularity smh
Can you guide for it me tommorow pls?
exit command
My bot on 6 server yet
ModuleNotFoundError: No module named 'discord.ui' What to do?
Do pip install
I surely can for sqlite, dont have much experience with postgreSQL
Not editor command, like actually in the terminal btw
Never
oh i tried that, but i was calling it xD
Do pip install discord.ui
no
I also installed
that's not how 😭
Kek, also sp? I usually find sp to be eh so I use vs
No
I just used it for views
oh god
No big Brian
I installed it, but it didn't help
Anyway bye good night sweet dream
You help
You have big brain :)
lmao bye good night
yes
refer to my message link
meh
🤣
Cool, I broke the bot.-.
🎉
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) What to do?
reinstall discord.py
i have a problem
Nice
today this shows and ```py
py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1
- py main.py
- ~~
- CategoryInfo : ObjectNotFound: (py:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException``` i get this error and if i do pip install nothing works
any ideas?
reinstall Python
do u actually need it
py is the basic Python launcher
if it isn't being recognized, that means a faulty installation
ok
try python instead of py before doing that tho
chances are, they haven't checked the "Add to PATH" checkbox, so that is why I said to reinstalled
py is added to PATH no matter u checked or not, that box
chances are he's gonna become a pro and add pip to path without reinstalling python
Let's hope for that
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1122, in call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 675, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 668, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ban' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'``` error , ```py
@client.tree.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason: str):
await member.ban(reason=reason)
await ctx.send(f"{member.id} has been banned for {reason}")
await member.send(f"You have been banned in {ctx.guild} for {reason}, Would you like to appeal? Join this server: hi")```
code ⏫
you can create slashed like that
the naming convention is wrong
its interaction, not ctx, and its Interaction.response.send_message
even the checks have to be imported from app_commands
How can I create cogs in the new version of discord.py?
same as 1.7.3 just that add_cog and load_extension are now coros
Not educational?
huh?
I'm educating people here?
u r
I wanna go drown in a glass of water again
!d discord.ext.commands.BucketType.default
The default bucket operates on a global basis.
!d discord.ext.commands.BucketType.user
The user bucket operates on a per-user basis.
You know what? #bot-commands exists
sorry...
Let me know how well that works for you
too late, she already gone
Does it take some amount of time or something for an application command to show up in a server? \🤔
hopefully she returns from her glass drowning shenanigans
Yes, ~1 hour for global commands
Commands registered to a single server are instantaneous
and that's with self.tree.copy_global_to?
I low-key tried it
thanks, Robin
i hate cogs
why 😭 cogs are one of the most appreciatable things in dpy
i cant use them, idk how to use that shit. bruh
what library?
To anyone who is hosting their bot on heroku. How would I go about editing the code after everything is set up. Do I have to push the .py file again or is there some kind of editor in heroku? I'm new to this so sorry if this is a silly question
updating your GitHub should trigger the update afaik
AttributeError: 'NoneType' object has no attribute 'is_connected' What to do?
@client.command()
async def play(ctx , arg):
try:
voice_channel = ctx.message.author.voice.channel
except:
print('Already connected or failed to connect.')
from discord import voice_client
if voice_client.VoiceClient.play(self=None, source=source):
await ctx.send(f'{ctx.message.author.mention}, the music is already playing.')
else:
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(arg , download=False)
URL = info['formats'][0]['url']
voice_client.VoiceClient.play(discord.FFmpegPCMAudio(executable="ffmpeg\\ffmpeg.exe" , source=URL , **FFMPEG_OPTIONS))
while voice_client.VoiceClient():
await sleep(1)
if not voice_client.VoiceClient.is_paused:
await voice_client.VoiceClient.disconnect()```
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
wdym? show example
hey there, repost w/o the server invite
anything with discord.gg in it will get flagged
what lib is this?
you wont have to redo all ur code
only some part of it
then refer to the docs of that lib
how do I make 2 embeds go?
use the embeds kwarg in the send method and pass in a list of embeds
What the heck does this mean?
TypeError: autocomplete callback 'name_autocomplete' requires either 2 or 3 parameters to be passed
I have
async def name_autocomplete(
interaction: Interaction,
current: str,
namespace: Namespace
) -> list[Choice[str]]:
...
Nevermind, I just removed namespace
it was on the Gist from Rapptz, but I guess it shouldn't be there
So i got a view and i passed in ctx but i get a error how else could i ban a user with a button because ctx will not pass in
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\lequi\Desktop\Hint Bot v2\cogs\user.py", line 199, in info
view.message = await ctx.send(embed = embed,view=view)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\context.py", line 771, in send
return await super().send(
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\abc.py", line 1541, in send
state.store_view(view, ret.id)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\state.py", line 368, in store_view
self._view_store.add_view(view, message_id)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 537, in add_view
view._start_listening_from_store(self)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 424, in _start_listening_from_store
self.__timeout_expiry = time.monotonic() + self.timeout
TypeError: unsupported operand type(s) for +: 'float' and 'Button'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'Button'
view = Whoisbuttons(ctx, member)
view.message = await ctx.send(embed = embed,view=view)
class Whoisbuttons(discord.ui.View):
def __init__(self, ctx, member, timeout=13):
super().__init__(timeout=timeout)
self.ctx = ctx
self.member = member
async def on_timeout(self):
for child in self.children:
child.disabled=True
await self.message.edit(view=self)
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user != self.ctx.author:
await interaction.response.send_message("You can't use that", ephemeral=True)
return False
return True
@discord.ui.button(label="Timeout",style=discord.ButtonStyle.green)
async def timeout(self,interaction:discord.Interaction,button:discord.ui.Button):
print("Test")
Discord.py is already u o date to the newest version
weird
Do you have an alternate?
It looks like You can’t name the function timeout
Because timeout is an attribute of view
Thank you :)
do you guys know a nsfw api(not anime, real)?
async def fetch_ids(ctx, channel, message):
if message.embeds:
text = re.findall('[0-9]+', message.embeds[0].description)
for i in text:
if not req.search_id(i) and not req.search(i):
req.add_id(i)
text = re.findall('[0-9]+', message.content)
if text:
for i in text:
if not req.search_id(i) and not req.search(i):
req.add_id(i)
I have an unknown trouble with this code. req.search(i) will return True if a given user id is in A table, False otherwise. req.search_id(i) will return True if user id is in B table, False otherwise. req.add_id(i) will add a given id to B table.
When I replace req.add_id(i) by print('Added'), and add print(req.search_id(i), req.search(i)), I can see that it prints Added only if both are False which is what I want. Also tested my the sql functions, they search and add just fine.
However when I run the above code, the following error happens:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: ids.subject_id
Which means req.add_id(i) tried to add an existant ID (since it's a primary key that has to be unique). The SQL request inside this function is INSERT INTO ids(subject_id) VALUES(?); and I know I can just add to the SQL that it will add only in subject_id doesn't exist, but I'm just curious why this doesn't work when the conditions are working fine?? this function is not supposed to receive ids that already exists it's triggering my curiosity so much !
I would learn so much if someone can help me understand where the problem comes from ♥️
what is req?
it's just a python file where I wrote my sql functions :D
Ah okay
Uh... How come message.content is always '' for me?
What module?
a module
i cant find any
@cerulean folio sorry I am not a SQL user, so u might wanna wait for someone like sarth/Robin to answer that
@cerulean folio nice big server you have there
Lol I can try
wdym?
This error means you tried to add a record with the same value as another one in a UNIQUE field
okie, thanks for trying my dude <3
no, i just mean that im amazed that you have such a big server. nice
Message received! message.content = ''
😔 why the heck
I know right, how's that even possible considering i'm checking if this value exists before adding it? D:
What module?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
oh thank you but, what server are you talking about? :o
I wouldn't have thought anyone was using anything else
Enable that in code and https://discord.dev
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
your?
i mean how did u know i have a big server? :o
bio
awww aw thank you ! 
Huh, that's new...
Yea, Discord API Changes
u can just do \d+ instead of [0-9]+
ohhhhh that's nice indeed thank you !
I tested it with the following code:
async def fetch_ids(ctx, channel, message):
if message.embeds:
text = re.findall('[0-9]+', message.embeds[0].description)
for i in text:
print('____________________________')
print(f'{not req.search_id(i)} and {not req.search(i)} gives:')
print(not req.search_id(i) and not req.search(i))
if not req.search_id(i) and not req.search(i):
print('Added')
# req.add_id(i)
text = re.findall('[0-9]+', message.content)
if text:
for i in text:
if not req.search_id(i) and not req.search(i):
print('Added')
print('____________________________')
# req.add_id(i)
Console output:
____________________________
True and True gives:
True
Added
____________________________
True and True gives:
True
Added
____________________________
True and False gives:
False
____________________________
True and True gives:
True
Added
____________________________
True and True gives:
True
Added
I don't know why my code won't work ><
The conditions are working fine, so home come req.add_id(i) receives an existing id as argument? 🤔
This drives me crazy it's not logical
what is req
Can i create a forum with a bot?
they are not even public
Hey @fallow girder!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
async def command_control_panel(self, ctx, member: discord.Member = None):
url = member.avatar.url # создал переменную URL аватарки пингуемого чела
url1 = requests.get(url, stream = True) # Сделал юрл более оптимизированным
url1 = Image.open(io.BytesIO(url1.content))
url1 = url1.convert('RGBA') # конфертировал аву в РГБА
url1 = url1.resize((300, 300), Image.ANTIALIAS)
sir, what could be wrong?
You used the command without mentioning a user
I'd prefer using case_insensitive instead of ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"]
Hey, bit of a difficult question, how do i set this to use better_exceptions instead of sys.stderr ? Basically what im asking is what file or whatever do i need to point it to
async def on_error(self, event_method, *args, **kwargs):
"""|coro|
The default error handler provided by the client.
By default this prints to :data:`sys.stderr` however it could be
overridden to have a different implementation.
Check :func:`~discord.on_error` for more details.
"""
print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
traceback.print_exc()
override the event
Oh right, thanks
font = ImageFont.truetype('./Шрифты/picsel.ttf', size = 100, color=())
Dear. what to write to change the color of the text?
yes, thats what that code is. what im asking is with what
wdym with what?
async requests
Hi,
I was trying to overwrite the owner IDs of the developer portal, due some reasons. But for some reason it doesn't work as expected:
bot = commands.Bot(command_prefix=commands.when_mentioned, test_guilds=[897866866557603890, 966350034822135878], sync_commands=True, intents=disnake.Intents.all(), owner_ids=[456458873453150208, 688293803613880334])
bot.remove_command("help")
If I do check for the owner IDs with an if statement:
if ctx.author.id == bot.owner_ids
It returns False for some reason
this is basic python. Print author.id and owner_ids and see if you can find out why you're getting False
bot.owner_ids is a list of ids, you are checking if the id of the user who ran the code is IN the list so you should do if ctx.author.id in bot.owner_ids:...
Has anyone developed a configuration system at scale? I need pretty advanced configuration (should support types and functionality that JSON/YAML supports) for each guild my bot is in. My bot has multiple services and processes which currently is an API, Redis cache, PostgreSQL instance, interactions endpoint, gateway subscriber/watcher and finally a proxy.
While the bot isn't big currently. I am interested in how software which scales is designed and maintained so I am writing up this bot.
Yeah I figured it out, it was a simple mistake by me. Thanks anyways
@commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
async def command_control_panel(self, ctx):
img = requests.get("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=12sxQbdr-1t3QUe8dp3Cy8ennHPq5fpsS", stream = True)
img = Image.open(io.BytesIO(img.content))
img = img.convert('RGBA')
idrawImg = ImageDraw.Draw(img)
font = ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)
author = ctx.author.name
tag = ctx.author.discriminator
text = f'{author}#{tag}'
idrawImg.text((330, 40), text = text, font=font, fill = (91,141,199,255))
url = ctx.author.display_avatar # создал переменную URL аватарки пингуемого чела
url1 = requests.get(url, stream = True) # Сделал юрл более оптимизированным
url1 = Image.open(io.BytesIO(url1.content))
url1 = url1.convert('RGBA') # конфертировал аву в РГБА
url1 = url1.resize((300, 300), Image.ANTIALIAS)
url1M = Image.new('L', url1.size, 0 ) # Создал картинку. Где L означает черно белая для маски нужна. url1.size перенимает size. 0 прозрачность
idrawM = ImageDraw.Draw(url1M) # говорим что переменной idrawM будем рисовать чтонибуить на url1M
idrawM.ellipse((0, 0, 300, 300), fill=255) # Рисуем элипс. координаты 0 с права, 90 с верху, 1850 ширина, 1800 высота. 225 непрозрачная
img.paste(url1, (406, 170), url1M)
img.save('./ImageS/profile.png')
file = discord.File("./ImageS/profile.png")
await ctx.send(file=file, view=class_control_panel(ctx.author.id))
Dear, can you please tell me whether it is possible to make the text, regardless of the length, be in the center of the picture?
this was my method
counter = 190 - len(member.name) * 10
img_editable.text((counter, 100), text, (0, 0, 0), font=font)
where 190 was the end of my image, minus 10 per character in the member's name
the problem was, some characters were longer than others
but you can go around that with a complicated method, that for example counts all i's in the name or w's, and it's minus 5 per i and minus 15 per w
Customized for yourself. works perfect. Thanks a lot. couldn't find it on the internet
I am trying to use cogs for a reload command, and it seemed to work, but now all of my other commands are broken because 'ctx' isnt passed in.
class Commands(commands.Cog):
@bot.command()
async def d(self, ctx, arg):
supported_docs = {
'python': 'https://docs.python.org/3/search.html?q=',
'discord': 'https://discordpy.readthedocs.io/en/stable/search.html?q=',
'pandas': 'https://pandas.pydata.org/docs/search.html?q=',
'numpy': 'https://numpy.org/doc/stable/search.html?q=',
'scipy': 'https://docs.scipy.org/doc/scipy/search.html?q=',
'pygame': 'https://www.pygame.org/docs/search.html?q=',
}
try:
# await ctx.send(arg)
arg = arg.split(' ')
# await ctx.send(arg)
arg = arg[0].split('.')
await ctx.send(supported_docs[arg[0]] + arg[1])
except KeyError as e:
arg = ctx.message.content.split(' ')[1]
key = 'python'
print(e)
await ctx.send(supported_docs[key] + arg)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
Without cogs, I didn't need to pass it in. It would automatically be there. Any ideas?
@bot.event
async def on_message(message):
if "https://twitter.com" in message.content:
string = message.content
vxtwitter = string.replace('twitter.com', 'vxtwitter.com')
webhook = await message.channel.create_webhook(name=message.author.display_name)
await webhook.send(content=vxtwitter, avatar_url=message.author.display_avatar.url)
it sends a message, and the on_message gets called
infinite loop
oooh so i acts like a loop ok
i know how to fix it thanks
Dear, tell me what kind of filter is this in the pillow
Why are you using bot in cogs
First time using cogs, I need an explanation on how it work not 'whys' and etc.
You use commands.command instead of bot.command in cogs
Try looking at the cogs examples and how to use them in the docs
extension
Hey @fluid shadow!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
with what do i replace sys.stderr with to use better_exceptions.
hello someone knows how to make a bot like this? with my current time + a dnd status
please dm
why even not
In discord bot have a command right and how do I make it so if I type like !restock and add a text file it reads it and writes it in another txt file
please help me
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
Whats the most popular library for making discord bots?
Most popular… either disnake or discord.py
Isn't discord.py discontinued?
like not maintained anymore
So now its fine to use it again without having to worry about it being discontinued again?
Fine to use it, yes. Worry about it being discontinued? Maybe
You being up a valid concern of how does one know if Danny won’t leave discord.py again?
Many are considering that, so good question
So maybe disnake is the better choice to learn? Which is "better"?
Better how?
You can make the decision for yourself of if you trust danny enough to continue developing it
Idk, which library is easier to use, has more functionality, etc
I can throw in my 2 cents but keep in mind it’s the opinion of a random guy on the internet
U know more than me so please fire away
Well, personally I believe discord.py is worth the risk, primarily because more people use it and ask for help with it. In terms of functionality, disnake and discord.py are almost identical, except for the different implementation but the end goal is still the same. Also disnake is relatively new, discord.py has been on for a good while and a de-facto, so there’s that
hm alright, would it be a big transition if I switch from discord.py to disnake later down the line?
Shouldn’t be. Disnake is a discord.py fork anyway
You should also keep in mind whether or not you can read documentation, if you can’t you’ll probably end up relying on guides, there will be a difference in the available guides for each wrapper
Wdym can read documentation? Like if I understand it or not?
Yes
The fork and the original will have different documentation as they bridge apart further
I usually do. Is that something some people struggle with?
I mean its boring asf but i get it
Yes some people try discord.py without some preq knowledge
But if you can read it, then you’ll be fine
great ty
I do find discord.py’s documentation to be a bit lacking when it comes to depth, like they don’t explain some of the API aspects very well
Ah, is disnake better in that regard?
I really have no clue, I haven’t taken a look so I’ll let you be the judge of that
I do know the maintainer has a lot of knowledge with the API and the gateway though
Same goes with discord.py’s maintainer
yup
I don’t know of anything called a “static token” and also it’s discord.Client, not discord.client?
that's discord.py logging in logging
for some reason dpy 2.0 turns logging level to INFO
Well yeah I know of the logging module, though not sure what a static token is
afaik it's always been logging like that since 1.0
Ah, so things are working as intended?
i think so
Have you tried restarting the script?
How could I fix this?
I am reworking this into a database 🤔
Oh ok thanks
I did this for 1 server, and it worked fine when I put a channel ID in
But I want it in a database 😅
I think it just refers to the normal token
static means non-changing iirc
Yeah
yo @sick birch do you know how to do this?
So you want to print exceptions from the be module instead of default ones?
yes
what i put there is the code to do that, but im just not sure what to replace sys.stderr with
Set that environment var
And it's gonna print automatically
(Acc to me it should)
been there, done that, found it does not work, found that you have to have this code, don't know what to replace sys.stderr with.
U don't replace that. sys.stderr represents the console, where the error is printed by default
ok what part needs to be replaced then
Try removing the traceback.print_exc()
why
Well, u need to try everything since I can't find the docs for the module that explain how to use it in the code
If you don't know how to help maybe don't just say i should "try everything" lol
This happened with me too
But next time i clicked on all check boxes and installed idk how it worked
@scarlet sorrel how r u setting the environment variable?
what environment variable
oh the one for better_exceptions
Yes
dude iv already looked through all that, its all good, but you need to do some special stuff for coroutines
dude i have better_exceptions working
Then?
I mean, what special stuff u talking about? For printing errors or smth?
yes obviously printing errors
better_exceptions/__init__.py lines 45 to 50
def format_exception(exc, value, tb):
# Rebuild each time to take into account any changes made by the user to the global parameters
formatter = ExceptionFormatter(colored=SUPPORTS_COLOR, theme=THEME, max_length=MAX_LENGTH,
pipe_char=PIPE_CHAR, cap_char=CAP_CHAR)
return list(formatter.format_exception(exc, value, tb))```
Try using this function
yes i already know it works
oh you mean try that instead of the other one
ok 1 sec
thats not better_exceptions
.....?
what even is this
The be GitHub
yea but what is that file
The _init_
what do i do with it
Bro what r u even tryna convey
what do i do with that code, just run it once and it fixes it, or put it at the start of the main file, or put it in the same folder or what
Have u ever used traceback.format_exception?
nope
Ah, well it's just like traceback.print_exception, but it instead returns the list of lines of the exception
ok well how do i make better_exceptions work for a coroutine/discord bot lol
So, better_exceptions.format_exception does the same thing. It returns the list of lines of the exception. U can change it to better_exceptions.format_exception(type(error), error, error.__traceback__)
In the on_error ^^^
but I don't have that line anywhere
did i need to put better_exceptions.format_exception in the .py file for it to work? it works with other stuff
i dont have "on_error event"
Dude async def on_error
🤷♂️ no one told me this lol
In dpy, everything prefixed with on_ is an event
everyone said better_exceptions just works
and you dont need to add anything
ill add it now
hi people !
somehow bot.fetch_user(764893681240637442) returns me this error:
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 user_id: Value "Unknown" is not snowflake.
@maiden fable
here's the function where i use it:
async def search_id(bot, arg):
try:
return await bot.fetch_user(arg)
except discord.NotFound:
return False
Bro...
it works whatever you send it normally, i don't know why it won't work with this particular id :o
u said delete everything and put only that in it
i love your profile picture !!! so nostalgic 😭
hahahaha
it used to scare the shit out of me now i somehow find this thingie so cute
dont mind us we're just enjoying the sights :)
wads are lt typhon ( https://forum.zdoom.org/viewtopic.php?t=64378 ) and lost civilization ( https://www.moddb.com/mods/lost-civilization )
bro what 😭
I meant, to delete everything inside the function
but i did do that, no?
This isn't #ot0-psvm’s-eternal-disapproval
D++ is a discord bot framework
No. U also rewrote the function. I meant to do:
async def on_error(error):
# Add that line here
It's for C++ not Python, sooo
yes?
Python is partly written in C++
C*
Yesss
Also, wait... The client.event isn't gonna work
Do u know about subclassing? @scarlet sorrel
that took ages for us to get on the same page
no
what repo?
cpython 
And do client.on_error = on_error before bot.run
im kinda an outlier when it comes to coding, i only learn something new when i cant just work it out or use a way of doing it that i already know, and i only use coding to do things that i want to do, so i end up with a weird set of knowledge where im really good at string manipulation and AI prompt formatting stuff like that but i barely know how to make a function
thats not even 1% lol.
thats why he did the emoji
Half if not the majority of the files being flagged are headers in include/ which are being falsely detected as CPP, it would make sense to me if was an .hpp but it isn’t, and the rest are just tests using CPP
And utilities ^
most of them are just .h files
Yes, they are being falsely flagged as CPP files
@maiden fable
I would accept if they were HPP files but they are just regular H files
And they don’t even utilise any of the stuff in CPP
In the on_error function
add error argument to your on_error function
Do on_error(error, *args, **kwargs):
He already has it
like this tho?
try it and see
oh, might me that then
thats where i got
.
await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.
Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
Gotcha. Do on_error(event_method, error): then
in the def on_error or just before the client.run?
Def
says its unused
It's fine
HAHAHzlhfùzlehgezN OOOOOO It's so cute 😭
ikr
why does it say "message" object, error shouldent be message
hi people !
somehow bot.fetch_user(764893681240637442) returns me this error:
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 user_id: Value "Unknown" is not snowflake.
here's the function where i use it:
async def search_id(bot, arg):
try:
return await bot.fetch_user(arg)
except discord.NotFound:
return False
I always have a bad feeling coming here
have you seen it tho, it is indeed so cute
makes me wanna kick it like a ball
it probably wouldent mind
I'm fine thanks, okimii is the cutest kid in this channel rn
HELP
!?!?!?
thats @slate swan pfp btw
@slate swan can you help me now?


Wtf image is this.......
fr
its @slate swan's profile pic
its just a female eating ice cream bro
Ok
nothing wrong with it
ice scream
yes i scream
what are you passing in search_id when calling it?
yea
i hate it when i press alt esc smh
tf does that even do
its a shortcut i have lol
more like a macro
and integer
but even if i pass 4484 or 68438438 or ,fmlerzgu it will not send this one error
...?
what? 
?
@commands.command(hidden=True)
@commands.guild_only()
async def sync(self, ctx: commands.Context, sync_globally: bool = False) -> None:
async with ctx.channel.typing():
if ctx.channel.permissions_for(ctx.author).manage_guild:
if sync_globally:
await self.bot.tree.sync()
await ctx.reply('Slash commands have been synchronized globally')
else:
self.bot.tree.copy_global_to(guild=ctx.guild)
await self.bot.tree.sync(guild=ctx.guild)
await ctx.reply('Slash commands have been synchronized on this server')
else:
embed = discord.Embed(title='Action Error', description='You don\'t have the permission to use this command.',color=0x2f3136)
embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/971007299038621727.webp?size=128&quality=lossless')
embed.set_footer(text=f'Requested by {ctx.author}')
await ctx.reply(embed=embed)
is this correct ?
it just shows tht my bot is typing but does not sync the commands
this command used to work before
does anyone know how to make a global chat for discord bot python
wdym by global chat?
just lile yggdrasil ig
like*
you dont really have to pass in the guild kwarg in sync since you're copying it all commands already
isn't that name of the world tree in Norse mythology
ik a bot name
It has welcome stuff
just fun facts
on_message send that message to every guild by iterating and sending
guys can someone help me with a sql request?
I need to SELECT * FROM tableA WHERE value1 < 3 AND NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID) basically, but there are fragments that i don't know how to do
idk i'm confused
It's better if you ask in #databases, since it's an sql question
yes !
Sqlite is very difficult to use
What's difficult about it
Everything
Maybe you just haven't learn much about it?
Today sqlite broke my brain
Me was making custom prefix for my discord bot
But finnaly i gave up
sqlite3 is easier than most of the databases, and a prefix system is really easy to implement
Ok help me at dm
@slate swan
Whats meaning of setup_hook
how can i have a clickable link in embed description
anyone here?
didn't work
show code?
i mean
like is it possible to have it without the https link
like it goes to www.google.com instead of https://google.com
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
bruh, www.google.com is not a hyperlink.
ooooooooooh i get it
my bad
There should be https in front
Ig
not really.... connect to db, execute query in db, close db
Me never used sqlite
Can you help me ?
I'll not ask for everything just help where i get stuck
yeah sure
just here
Ok
oh wait #databases is better
peeps can u give feedback about my bot https://github.com/Code-Theft-Auto/sockeyPy
a discord.py music and general purpose bot . Contribute to Code-Theft-Auto/sockeyPy development by creating an account on GitHub.
main.py line 24
await bot.change_presence(activity=discord.Activity(type=beats_activity[0], name=beats_activity[1]),status=discord.Status.dnd)```
`modules/impfunctions.py` line 30
```py
response = requests.get("https://memes.blademaker.tv/api?lang=en")```
`cogs/general.py` line 97
```py
for guild in self.bot.guilds:names.append(f"**`{guild.name}`**")```
don't change status in on_ready
um wot can i do?
use async libraries, aiohttp in your case
maybe can u do a pr?
and you can use a list comprehension instead of that for loop
!listcomp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if statement:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
sed only poor tuple dosent have a comp generator kicked it out
