#discord-bots
1 messages ยท Page 230 of 1
Why do you need to constantly close it and open it?
just to edit the code
I usually use extensions to hot-reload
But there's really nothing with re-starting the bot in development as you work on it
In fact it's easier and faster than having a dedicated command to shut down the bot
right so just opening and closing is faster?
what are extensions, im very lacking in the theory
they're just files you can load, reload, and unload in discord.py
interesting
A debugging and testing cog for discord.py rewrite bots. - GitHub - Gorialis/jishaku: A debugging and testing cog for discord.py rewrite bots.
this provides commands for reloading extensions and debugging commands
and syncing slash commands if you're going to make those
maybe for later, it does seem kinda complicated
if you have it installed all you need is await bot.load_extension("jishaku") in a setup_hook event
async with aiohttp.ClientSession() as session:
ofww = open(f'users_data/{ctx.guild.id}/impset/lw.json', "r")
wfc = ofww.read()
ff = json.loads(wfc)
info = ff['webhook_logs']
webhook = Webhook.from_url(f'{info}', session=session)
await webhook.send('Hello World', username='KalKer Logs')
huh ?
Can you show us the contents of lw.json?
Should be info = ff['webhooklogs'] then
pretty sure it has a scheduling system
it uses redis probably
or site-api
yes it will
oh wait
you have to check the audit log
ohhhhhhh ok my bad lmao
did you save your code..?
the error is not showing the same code
as the one you sent
you reassigned message
!d discord.AuditLogEntry
class discord.AuditLogEntry(*, users, integrations, app_commands, automod_rules, data, guild)```
Represents an Audit Log entry.
You retrieve these via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
x == y Checks if two entries are equal.
x != y Checks if two entries are not equal.
hash(x) Returns the entryโs hash.
Changed in version 1.7: Audit log entries are now comparable and hashable.
Where did you get the idea that the object has a channel attr
he reused a variable name
๐ฎ
ยฏ_(ใ)_/ยฏ
What are some free services I can use to host a discord bot?
does disnake keep up with upstream?
Check out the pinned message in #965291480992321536 (you can also use the channel to ask for help about discord bot hosting)
Seems like it
i'm not sure if that's possible
just check the timestamp of the audit log entry maybe and see if it's equal to the current time
if not then the deleter is the author
probably
discord.on_audit_log_entry_create(entry)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") gets a new audit log entry. You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to receive this.
This requires [`Intents.moderation`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.moderation "discord.Intents.moderation") to be enabled.
New in version 2.2.
Warning
Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the [`AuditLogEntry.target`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.target "discord.AuditLogEntry.target") attribute will usually be a [`discord.Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") and the [`AuditLogEntry.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user "discord.AuditLogEntry.user") attribute will depend on user and member cache.
To get the user ID of entry, [`AuditLogEntry.user_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user_id "discord.AuditLogEntry.user_id") can be used instead.
huh, thats neat
why do i get this error?```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "/home/runner/MathBot-1/cogs/paper.py", line 414, in paper_result_check
value="\n".join((await server.fetch_member(i)).mention for i in document["approvals"]),
TypeError: can only join an iterable
First of all, you will be making excessive API calls while you can do that completely without them simply by putting id into mention placeholder
f"<@{i}>"```
Second, what is `document["approvals"]`? Could you print its contents?
is there a way to find the original message id from a button? im trying to figure this out but cant quite | edit : nvm i figured it out
its a list of member ids```py
[719807591869317201]
only one member currently but it can also have more
actually i think i fixed it
Well good luck with finding another method (it probably doesn't exist)
Alright just make sure to use my method of getting mentions, you don't need whole member object just for mention
aight thanks
e
im trying to make a timezone command does anyone know a thing i can use to turn what the person inputs into a datetime.datetime ?
does anyone have expirience in Selfrole but with buttons? I have a thread open if someone could help, that would be awesome https://discord.com/channels/267624335836053506/1098510816694771752
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
What do you mean exactly?
The person Input a time zone or location like london England gb or utc gmt etc and then it returns the current time at the time zone
You could use pytz and datetime
import pytz
from datetime import datetime
timezone = pytz.timezone(location)
current_time = datetime.now(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')
Thatโs a general example, where location is a string of your location
kk thanks ๐
I just noticed the built in paid subscriptions inside bots ๐
I mean I gotta love Discord encouraging people making their own bots!
how do i make the bot delete the command message
slash command or normal command
no like i type
!spoiler example
and it deletes the command message
original message*
so normal command
what is it
ctx.message.delete() ?
yes
ok thanks
It suits you โบ๏ธ
Yeaaaaa!
Click on โจ and hold the popup image that comes
Nothing comes
First click on the emoji
Then hold the preview image which comes
Make sure u r on the latest version
English only please
How to switch back
Hahahahaha hated it?
Yes
The same procedure
Everything is too big and round
Lmao discord just made the UI more confusing for newbies
I do prefer some curve ya know but it's a bit much
๐
If it aint broke don't fix it
But no fr it's impossible to find channels if there are a lot lol
I guess the choose your channels on top is nice
But it's shared across desktop..
True
is this the correct way to load a cog ?
@bot.slash_command(name="load",guild_ids=GUILD)
async def load(ctx: discord.Interaction,extension:str):
if(ctx.author.id in ADMINS):
try:
print(extension)
bot.load_extension(f'{extension}')
await ctx.response.send_message("Cog loaded.",ephemeral=True)
except Exception as E:
await ctx.response.send_message(E,ephemeral=True)
raise E
if so, my commands aren't being registered if i unload any command and then load it again
You also have to sync the commands
What lib is that ๐ง
pycord
And you can also setup permissions outside the command and handle it your error handler.
And it's best to specify the error since there isn't much that can go wrong.
I understand. i will look into it
thanks
looks much cleaner thanks for the advice
Is there any way to simplify this code?
Any reason why you pass the api key every time?
I thought I have to do that to make a API request
I meant in a call like this -> await get_summoner_name("na", summoner_id, "API_KEY", True)
I know the code you work with and you have multiple sessions each time but it's more efficient and cleaner if you make one session and keep passing that. You'd also not need to re-send the token since it's inside the session. You do need to make something if the session gets destroyed.
Don't know exactly what you are trying to do but when working with an API I like to have/make a wrapper for it so I don't have to make a function for each item.
@cloud dawn I see. Could you review the code if I send it over to you?
I could.
why isnt the bot able to ping the role?
I have checked the follwing things: I have the role, The channel perms are correct, The bot has an admin role โ
I mean I know this isnt the right channel but like its a small doubt
(sorry for that it was late before I realised that ๐ฅฒ )
Did you change the mention settings inside the bot?
no, not specifically, could you explain a little?
sorry i am a little new :P
I have intents enabled if thats what you meant
intents = discord.Intents.all() intents.members = True intents.guilds = True intents.message_content = True intents.voice_states = True
I meant the mentions settings specifically but I don't think you have.
how do I do that??
If you're specifying all why are you still defining others?
By default it's unchanged.
Great! DMed it to you. We can keep the conversation here, it's just for the code.
How could i limit attachment size through a slash command ?
as in? a little confused right here
what exactly do I do to make that work?
You'd need to change the actual resolution.
It's not something you'd need to manually disable it, unless you copied the bot.
the role?
I know but it's the way Discord behaves with images.
i dont understand, i want to reject the slash commands that have been used with an attachment of greater size than specified
Ahh that can be done.
wont an if else statement help?
!d discord.Attachment.size
The attachment size in bytes.


Understandable 
!d discord.Attachment.height
The attachmentโs height, in pixels. Only applicable to images and videos.
don't really need resolution, just size limitations
I see it also has options for sending attachments with size.
so like
if discord.Attachment.size >= <limit>:
await ctx.respond("Bro damn, its huge.... the image. The image bro")
``` ๐
anyways @cloud dawn a lil brainstorm on my problem please ๐
No, you need an attachment instance
yea yea... got that ๐
Only thing I can think of rn is your guild settings. Is it set as a community? Those sometimes mute pings.
yes... its community enabled
wait let me send you my code
@discord.slash_command(name ='test1', description="this is a test command :D")
async def test(self, ctx):
embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : `/bump`")
await ctx.respond("<@&1083433733857755269>", embed=embed)
theres a high chance something maybe wrong here
this is pycord btw
So for the code you can make an async session outside of the functions and pass the session along with it.
await ctx.respond(ctx.guild.get_role(1083433733857755269).mention, embed=embed)
Ig try that, it shouldn't matter but if you think it's the bot itself.
yea yea
@cloud dawn so... ctx.respond does not allow a ping
but ctx.send did
That's... odd
see
the interaction failed because i did not mention ctx.responf
@discord.slash_command(name ='test1', description="this is a test command :D")
async def test(self, ctx):
guild = self.client.get_guild(1075617310540308583)
role = utils.get(guild.roles, id=1083433733857755269)
embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : /bump ")
await ctx.send(role.mention)
but neverminf
I was just checking if this would work
originally this embed and ping was meant for a bump reminder message, that would be triggered a certain message in a channel
thanks @cloud dawn for all suggestions :)
np :)
what would i need to unload a command ?
@bot.slash_command(name="unload",guild_ids=GUILD)
@commands.is_owner()
async def unload(ctx: discord.Interaction, extension: str):
await ctx.response.defer(ephemeral=True)
bot.unload_extension(f'{extension}')
await ctx.followup.send("Cog unloaded.", ephemeral=True)
i have also tried syncing
@cloud dawn Should I keep on_ready in this code or move it somewhere else?
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
async def on_ready(self):
print('Bot is ready!')```
why would you ever need to unload a command
On ready is fine as long as it doesn't matter if it gets executed again after startup
well to load it back again -_-
after making modifications
Well reload exists
Iirc, unload_extension is async
Disnake even has a dev mode that auto reloads cogs on change.
I see
Helllo! Yesterday I changed my discord bots image on the developer portal, but the image does not change.. Does anybody knows how I can solve this?
class PaginationView(discord.ui.View):
current_page : int = 1
sep : int = 6
async def send(self, interaction: discord.Interaction):
self.message = await interaction.response.send_message(embed=self.create_embed(self.data), view=self)
await self.update_message(self.data[:self.sep])
async def update_message(self, data):
self.update_buttons()
await self.message.edit(embed=self.create_embed(data), view=self)
def create_embed(self, data):
embed = discord.Embed(title=f"๐ information ({self.current_page} / {int(len(self.data) / self.sep) + 1})")
for item in data:
embed.add_field(name="testing", value="test", inline=False)
return embed
await self.message.edit(embed=self.create_embed(data), view=self)
๏ปฟAttributeError: 'NoneType' object has no attribute 'edit'```
how to fix it so that the post is editable?
!d discord.InteractionResponse.send_message - the method doesn't return the sent message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
!e
import json
string = """{
"cat": "meow\nuwu"
}"""
print("Doesn't error")
json.loads(string, strict=False)
print("Error")
json.loads(string)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Doesn't error
002 | Error
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 11, in <module>
005 | json.loads(string)
006 | File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
007 | return _default_decoder.decode(s)
008 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
009 | File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
010 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
011 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/edolividen.txt?noredirect
!d json.loads
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *s* (a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray") instance containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
The other arguments have the same meaning as in [`load()`](https://docs.python.org/3/library/json.html#json.load "json.load").
If the data being deserialized is not a valid JSON document, a [`JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError "json.JSONDecodeError") will be raised.
Changed in version 3.6: *s* can now be of type [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray"). The input encoding should be UTF-8, UTF-16 or UTF-32.
Changed in version 3.9: The keyword argument *encoding* has been removed.
??
and how to make, that returned and the message was edited?
help please
??
it's working for my other script, but this not for this one idk why
anyone knows if there is something like this for a app_commands.Group?
class itemFunctions(app_commands.Group):
async def cog_app_command_error(self, interaction, error) -> None:
if isinstance(error, app_commands.errors.CommandOnCooldown):
embed = discord.Embed(
description=f"โ | Youre repeating to fast! **Retry in {round(error.retry_after)} seconds**!",
color=error_color)
await interaction.response.send_message(embed=embed, ephemeral=True)
else:
print(error)
of course this one is for a cog
Traceback (most recent call last):
File "C:\Users\user\Documents\calculator\main.py", line 10, in <module>
config = json.load(open("config.json", encoding="utf-8"))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 4 column 1 (char 126)
huh ?
import discord
from discord.ext import commands
bot = commands.Bot(intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
bot.run('bot token lol')
i haven't kept up with slash commands, can anyone please tell me how to make a slash command?
just do json.load(open("config.json"))
is there a way to add {} into the modal pop up? doing a welcome command with different variables and stuff
anyone know how to make a slash command with like
/mute user:id duration:60d
like how do i make a option
nvm found a way
it's an error about your config.json file
btw opening and reading a file is a blocking call, this mean that it'll block the bot's event loop
you should use something async or run that function with an asyncio thread safe function
@client.tree.command()
async def hello(interaction: Interaction):
print(f"> {Style.BRIGHT}{interaction.user}{Style.RESET_ALL} used the command.")
await interaction.response.send_message(inspect.cleandoc(f"Hi **{interaction.user}**, thank you for saying hello to me."))```
can someone help me add an option here, doesn't matter what it is
!pypi aiofiles
it just worked for me this morning
i changed nothing
check your json file
at line 4 there's a json syntax error
like this
check it's content :
{
"bot_token" : "---MY BOT TOKEN---",
"bot_status" : "By Medra#0002",
}
{
"bot_token" : "---MY BOT TOKEN---",
"bot_status" : "By Medra#0002"
}```
try that lol
this is still an issue
i still need to know how to do this
yeah ik, thanks for your help ๐ซ
is there a way to check the webhook "owner"? by owner i mean the integration that created it, in this case mine. i want to get all of the webhooks on a x channel that was created by myself (via TextChannel.create_webhook) and use this webhook to send a message instead of creating a new one
i was thinking to loop through the webhooks of a channel TextChannel.webhooks() and checking the "owner" of each one of them, them if i find one that is from my integration, i just get the url from it and construct it again with Webhook.from_url, but if you have another solution let me know
you just need to pass them as arguments
async def hello(inter: Interaction, member: discord.Member, time: int, reason: str): ...
they will all be mandatory instead if you want to make them optional you just need to pass a default value for that argument
Probably should apply a transformer to the time
!d discord.Webhook.user
The user this webhook was created by. If the webhook was received without authentication then this will be None.
for simplicity I did it as int 
Ye just a suggestion to OP
Hello! Yesterday I changed my discord bots image on the developer portal, but the image does not change.. Does anybody knows how I can solve this?
am i dumb or why does this not work?
if self.image.value is not None:
if not re.match(r'\b(https?://\S+\.(?:jpg|jpeg|png|gif|bmp|webp))\b', self.image.value, re.IGNORECASE):
return await interaction.response.send_message("You did not provide a valid URL to an image in **Embed Image (right-placed)**.", ephemeral=True)
elif self.image_bottom.value is not None:
if not re.match(r'\b(https?://\S+\.(?:jpg|jpeg|png|gif|bmp|webp))\b', self.image_bottom.value ,re.IGNORECASE):
return await interaction.response.send_message("You did not provide a valid URL to an image in **Embed Image (bottom-placed)**.", ephemeral=True)
else:
await interaction.response.send_message(f"You have successfully configured your Embed, see how it looks: `{ctx.prefix}welcome show`", ephemeral=True)
in the docs it says when no text is input its None
what's not working
so if self.image.value or self.image_botton.value is not None, it should match the regex etc.. but if its not it should skip that part and go to the else statement, but even if its None it still goes to the if or elif statement
uhm yeah.. nvm i fixed it
thanks ๐
how do y'all construct embeds? out of curiosity
embed = (
discord.Embed(
title="some_title",
color=discord.Color.brand_green(),
)
.add_field(name="some_field", value="some_value")
.add_field(name="another_field", value="another_value")
)
or
embed = discord.Embed(
title="some_title",
color=discord.Color.brand_green(),
)
embed.add_field(name="some_field", value="some_value")
embed.add_field(name="another_field", value="another_value")
you just need to pass an url to the url kwarg and discord.ButtonStyle.url to the style kwarg
!d discord.ButtonStyle.url
thx
!e
code
!e ```lua
--...
function string_split(inputstr, sep) --ln 3 (i didn't make this function)
sep = sep or "%s"
local t= {}
local pos = 0
local function next(s)
pos = pos + 1
local out = s:sub(pos, pos) --ERROR!(attempt to call method 'sub' (a nil value)) (errors when called from ln 79, but not the ln 61 call)
if out ~= "" then
return out
end
end
local cur_str = ""
local next_char = next(inputstr)
while next_char do
if next_char == sep then
table.insert(t, cur_str)
next_char = next(inputstr)
cur_str = ""
else
cur_str = cur_str .. next_char
next_char = next(inputstr)
end
end
table.insert(t, cur_str)
return t
end
--...
function deserialize(serial) -- ln59
local values = string_split(serial, "|") -- ln 61
print(tostring(#values))
if values[1] == "runlogger" and #values == 10 then
local seed = tonumber(values[2])
local death = values[3]
local time = tonumber(values[4])
local killed = tonumber(values[5])
local hp = tonumber(values[6])
local gold = tonumber(values[7])
local x = tonumber(values[8])
local y = tonumber(values[9])
local wandstogether = values[10]
print(wandstogether)
local wands = string_split(wandstogether, "^") -- ln 79 (ERROR!!!)
--...
else
print("Invalid format!")
end
end```
!e ```lua
--...
function string_split(inputstr, sep) --ln 3 (i didn't make this function)
sep = sep or "%s"
local t= {}
local pos = 0
local function next(s)
pos = pos + 1
local out = s:sub(pos, pos) --ERROR!(attempt to call method 'sub' (a nil value)) (errors when called from ln 79, but not the ln 61 call)
if out ~= "" then
return out
end
end
local cur_str = ""
local next_char = next(inputstr)
while next_char do
if next_char == sep then
table.insert(t, cur_str)
next_char = next(inputstr)
cur_str = ""
else
cur_str = cur_str .. next_char
next_char = next(inputstr)
end
end
table.insert(t, cur_str)
return t
end
--...
function deserialize(serial) -- ln59
local values = string_split(serial, "|") -- ln 61
print(tostring(#values))
if values[1] == "runlogger" and #values == 10 then
local seed = tonumber(values[2])
local death = values[3]
local time = tonumber(values[4])
local killed = tonumber(values[5])
local hp = tonumber(values[6])
local gold = tonumber(values[7])
local x = tonumber(values[8])
local y = tonumber(values[9])
local wandstogether = values[10]
print(wandstogether)
local wands = string_split(wandstogether, "^") -- ln 79 (ERROR!!!)
--...
else
print("Invalid format!")
end
end```
@toxic meteor :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 3
002 | function string_split(inputstr, sep) --ln 3 (i didn't make this function)
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 3)
is it possible to lock certain commands away from other users that they can not see it
add permissions for the command
i already told you though
did you
im sorry lol
i forgot abt it thanks tho
i'm doing this to respond to a interaction without doing anything, but i feel like its a bit hacky and i shoudnt be doing this. are there other ways to do this, without editing any mesages or doing any action really?
Yes, actually. await interaction.response.defer()
It tells Discord that you successfully received the interaction and acknowledged it, you just don't want to do anything at the moment
Only if you do await interaction.response.defer(thinking=True)
The thinking kwarg is False by dfeault
ah this works just fine, thanks
i though this would do some type of action independent of the kwargs set, but it appears that it just "pong" the interaction
i have certain variables stored in my db as a string, 1 example is "{user.name}", i want to convert it to the user name (i can do that), but the thing is that i normally wouldn't know which ones are stored so i need to "detect" them and convert them into the according real variable
talking about pong, what is InteractionResponse.pong() even used for? the docstring doesnt say much... could you make a example perhaps?
This should rarely be used.
I wouldn't worry about it
well, knowledge is never too much
If you want to know it's used as the appropriate response to an interaction from the Discord gateway with type 1 (PING)
when does discord fires this? 
The documentation is pretty sparse regarding that
I'm guessing the timing behind PING interactions is just internal
All the Discord API documentation says is "you must be ready to respond to a PING interaction with PONG at any time"
We see a similar system implemented in the gateway but it's documented better and more obvious (you need to keep ping-ponging the gateway to maintain a connection)
Yup
kk, thanks for the explanations ๐
!d discord.Client.get_partial_messageable
get_partial_messageable(id, *, guild_id=None, type=None)```
Returns a partial messageable with the given channel ID.
This is useful if you have a channel\_id but donโt want to do an API call to send messages to it.
New in version 2.0.
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Represents a link button.
could you gimme an embed example with link button, i don't understand it's syntax :/
@sick birch ๐
Im trying to set up a discord bot, im new to the bot things but not python,
I just cant get it to respond to my messages, I used this tutorial to get on with it https://youtu.be/hoDLj0IzZMU I even tried fixing it with the bot but it just didnt work,
Can someone take a look at my files please? Appreciate your time
Today we will be learning how we can create a Discord Bot from scratch in Python. We will host it on a local server and it will be able to respond to users in less than 15 minutes! A perfect tutorial for getting started with Discord Bots in 2022.
Developer Portal:
https://discord.com/developers/applications
00:00 Demo
01:30 Getting started
04...
Took a scrub through the video - it's pretty outdated and following bad practices
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
The above embed is most likely the cause of your issue
How do you trigger typing?
!d discord.abc.Messageable.typing
async with typing()```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.
Example Usage:
```py
async with channel.typing():
# simulate something heavy
await asyncio.sleep(20)
await channel.send('Done!')
``` Example Usage...
it's a context manager
Is it possible to do a leaderboard discord bot that will refreshes it every minutes or so?
yes but leaderboard for what
"is it possible" is a very vague question
Messages count
Well I want it to count how many message a user sent and be able to do a lifetime and weekly leaderboard that refreshes often
Is there any documentation to help me?
use a database and ext.tasks
!d discord.ext.tasks.loop
@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").
Is it better to use a dictionary or a tuple for returning functions?
Those are two very different things
So... I guess it depends entirely on what exactly you're doing
Looking for someone that can do discord bot work, paying in BTC
Hey i have used buttons in my discord bot
Like someone pressed the button it will dm etc
But after sometime of posting it , the button stops working
Also if i edit any code in my bot it stops working
yes because views have a default timeout of 180 seconds
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
i think you mean if you restart the bot
So timeout=None?
Yep
that would make it never timeout, if that's what you want yeah
then you would want a persistent view
Nice just add custom id
no...
you need no timeout and the add_view method is what actually makes it persistent
hello i seem to be having a problem with this line of code, i believe its been removed in v2 of discord.py but if anyone can help me find a replacement that would be greatly appreciated ๐
cogs = [c for c in self.client.cogs.keys()]
lower_cogs = []
for cog in cogs:
lower_cogs.append(cog.lower())
Ty but how can I make the command invisible to regular users
import discord
from discord.ext import commands, tasks
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def bump_reminder(ctx: commands.Context, action: str):
disboard = ctx.guild.get_member(302050872383242240)
if ctx.channel.id != 1098629989794066486:
await ctx.send("Use this command at the bump channel")
return
if not action.casefold() == "bump":
return
if not disboard.status == discord.Status.online:
await ctx.send(embed=(discord.Embed(color=discord.Colour.red,description=(f"Whoa {disboard.mention} appears to be offline right now!\nI'll monitor the bump bot's status and notify everyone when it comes back online."))))
return
else:
await ctx.send("thanks for bumping,disboard will be back in two hours to be bumped:)")
await ctx.channel.set_permissions(disboard, view_channel=False)
lock_disboard_Out_for_two_hours.start()
@tasks.loop(hours=2)
async def lock_disboard_Out_for_two_hours():
guild = bot.get_guild(1098629989794066483)
disboard_role = discord.utils.get(guild.roles, name="DISBOARD")
bump_role = discord.utils.get(guild.roles, name="Bumpers")
channel = guild.get_channel(1098629989794066486)
await channel.set_permissions(disboard_role, view_channel=True)
await channel.send(f"Discord is back, {bump_role.mention} come bump the server!")
lock_disboard_Out_for_two_hours.cancel()
bot.run('token')
I am trying to make a disboard remainder bot i dont know its dont even responding, Can anyone can help me?
how should i fix missing 1 required keyword argument intents on discord py?
By passing the required keyword argument? Seems quite self explanatory
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
hey i got this error
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
``` but the bot works just fine... is it concerning or do i let it be?
...
I found this to be the easiest way:
intents = discord.Intents().all()
client = commands.Bot(command_prefix=get_prefix, intents=intents)
What about it
It doesn't have a bot keyword argument as the error says
so what should i do
to run the bot
Don't pass bot keyword argument?
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
Selfbots violate discord ToS
Selfbots are against ToS
We don't help with that here and discord.py does not support them
Not sure what you mean by that
bot.run(token) or client.run(token)
let me check
i ve try to code "bot=True" but this displayed
Just don't pass it
What
What do you mean it cannot run
If you have a bot token and you pass it to .run() it will run
bot.run() right?
as shown here ^
can anyone help i get this error when i try and run my bot aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1002)')]
how can i make a bot where if he sees any embed with #ff0000 he will respond i see a embed with #ff0000
!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)
you wanna do on_message and go though for embed in message.embeds then if embed.color == 0xff0000 do whatever
what if a bot send a embed will it work
Any1 Can help me and tell me Which vps-plan from here: https://www.ionos.de/server/vps is the Best to host a python Discord bot?
Thank you
i think so
okh
Any you like, hosting is dependant on you, and understanding the resources required to host and run your bot without any issues.
import discord
from discord.ext import commands
import asyncio
# URL of the image to use in the embed
embed_image_url = 'https://images-ext-1.discordapp.net/external/tAuRcs-FCy2M8OaTS9Ims62J1vrFiviahjBDtpZrrBs/https/disboard.org/images/bot-command-image-bump.png'
# Create a new bot with a command prefix of "."
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)
# Define an event handler that will run every time a message is received
@bot.event
async def on_message(message):
# Check if the message content is "/bump"
if message.content == '/bump':
# Check if the message contains an embed with the specified image URL
if message.embeds and message.embeds[0].image and message.embeds[0].image.url == embed_image_url:
# Get the name of the user who sent the message
author_name = message.author.name
# Send a message saying that the user just bumped the server
await message.channel.send(f'{author_name} just bumped the server')
else:
# If no embed with the specified image URL is found, send a message saying that no one bumped the server
await message.channel.send('No one bumped the server :(')
# Process the message as a command, if it matches the command prefix
await bot.process_commands(message)
I am working on a bump remainder but i got a issue in the half of the development, the issue is its not even able to recognise who bump with /bump command, Any help would be appreciated.
That's not how you use slash commands
And because you have a Bot instance it makes sense to never write commands in an on_message event in the first place
can you explain me how can i use that
?
Do you want it to be a slash command, a message command or a hybrid command?
it is a slash command but i want my bot see it on_message
you wouldn't want to do that
@bot.event
async def on_ready() :
logschannel = bot.get_channel(config['logs_channel'])
await bot.change_presence(status = discord.Status.dnd, activity = discord.Activity(type = discord.ActivityType.watching, name = f"{config} | {len(bot.guilds)} servers !"))
await logschannel.send(embed = discord.Embed(title = f"",
description = f"\โ
ใป Bot successfully connected and able to receive commands !",
color = 0x45b557))
it's status didn't change :/
"Instead of doing async setup in on_ready, or using a task which may lead to events being called before that task runs, you can overwrite Client/Bot.setup_hook.
For example:-
class MyBot(commands.Bot):
async def setup_hook(self):
print("Bot is starting")
await self.load_extension("my.extension")
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook"
Slash comnands are not messages therefore do not invoke that event
Actual response from bot might do that but I am not sure about that either
@bot.slash_command(name="help", description="CMD used to display commands help panel")
async def help(ctx) :
embed = discord.Embed(title = f"โ",
description = f"",
color = 0x2c245b)
embed.set_footer(text = config["footer_txt"], icon_url = config['footer_img'] )
await ctx.respond(embed)
huh ?
hm ?
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
I don't know if pycord does it differently, but in discord.py you have to specify you're sending an embed with embed=
@tall temple Look at the function.
could you explain ?
๐น
oh yeah i put embed = embed and it worked
thx
Well by looking at the function you can see what you need to pass in order for the function to work. In this case the first optional argument provided will be content. And in the Discord.py library it always get converted to string.
There are also multiple keyword arguments that are indicated by being after the * so in order to send the embed you need pass it along the right keyword. e.g embed=embed.
How do i reset the select drop-down menu after each iteration, cuz when the bot moves to next one and trys to add the options again, then it shows an error that the option already exists
await bot.change_presence(activity=discord. Activity(type=discord.ActivityType.watching, name = f'{config} | {len(bot.guilds)} servers !'))

?
the bot is not making watching status :/
I'll share my discord token , and see what you guys add ! , Idc if someone just deletes the whole server
But it will be fun to see what ppl adds
Will it be creativity or destruction
Dm me if someone agrees to accept it , I'll dm them bot token
you can't
there is a bot security
you can post your token here
try ๐น
I mean kicking ppl โ delete server
okok
Nope cant
@slate swan What intents are on?
Do u mean permissions?
Return two values and set them to the database ๐
intents
The intents option that appears on dev portal is on
@cloud dawn help pls ๐น
Yeah these are on
All three of these
Public bot , and these 3 are enabled @cloud dawn
I also tested token its working
I realised
This isn't weird experiment at all
This is what 99.99% servers go through
Trusting random bots
General chat id , [#1098955638073213089](/guild/267624335836053506/channel/1098955638073213089/)
hey when i restart my bot the buttons dont work how to fix it?
Hi there, I'm having issues with my code. I'm trying to make a roblox discord verify system. Essentially this is a "loop" where it does the following:
- Bot asks the user to enter their ROBLOX username.
- Bot reads the roblox username.
- Bot uses the ROBLOX API to get information about the user using this API: https://users.roblox.com/v1/users/search?keyword={username}
(username is the definition for the message content, basically the username they provided in step 2. - If the data is valid, ask if it's THEIR account.
-> If user says YES, the code should continue to go down further the loop (you can't see it in the code I sent, it's basically the code that's below it but not apart of it)
-> If user says NO, the code essentially resets. Basically, the code should go back to step 1 and ask for the users ROBLOX Username. All previous data should be wiped to make sure there are NO issues with calling the ROBLOX API. Essentially it should be like I just stopped the bot and turned it back on. Just not actually turning off and on, just resetting and going to step 1. - Else, if the data IS NOT VALID, it should do the same as the NO statement in step 4.
My current code, which doesn't work the way I described above,
while True:
await channel.send('Please enter your Roblox username.')
username_message = await bot.wait_for('message', check=lambda message: message.author == ctx.author and message.channel == channel)
username = username_message.content
url1 = f'https://users.roblox.com/v1/users/search?keyword={username}'
response = requests.get(url1)
data = json.loads(response.text)
if "data" in data and len(data["data"]) > 0:
user_id = data["data"][0]["id"]
print(user_id)
while True:
await channel.send(f'Is "{username}" your Roblox account? Please type "YES" or "NO".')
verification_message = await bot.wait_for('message', check=lambda message: message.author == ctx.author and message.channel == channel)
verification = verification_message.content.lower()
if verification == "yes":
await channel.send(f'{username}" has been verified with Roblox ID: {user_id}')
break # Exit the inner loop and continue with the command
elif verification == "no":
await channel.send('Please enter your Roblox username.')
break # Exit the inner loop and restart the command
else:
await channel.send('Invalid input. Please type "YES" or "NO".')
else:
await channel.send(f'Sorry, {username} could not be found on ROBLOX.')
import asyncio
import logging
import discord
from discord import Intents, Game
from discord.ext.commands import Bot
logging.basicConfig(encoding="utf-8", level=logging.DEBUG)
class Dispy(Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
@property
def latency(self) -> int:
return int(super().latency * 1000)
async def on_ready(self) -> None:
logging.info(f"Ready, {self.latency}ms")
await self.change_presence(activity=Game(name="YEEEEEEEEEEEEEET"))
async def setup_hook(self) -> None:
self.app_info = await self.application_info()
logging.info(
f"Starting {self.app_info.name} using discord.py {discord.__version__} - {discord.__copyright__}"
)
bot = Dispy(command_prefix="!", intents=Intents.all())
async def main() -> None:
async with bot:
await bot.start(
"MTA4NjY2NDA5NzY3Nzk4Nzk5MA.GdqSn Remove spacing b.maGqaUtglD8Mkk1aDGV2nP8dktbNCD7YqX-llg"
)
if __name__ == "__main__":
asyncio.run(main())
Here a template for everyone lol
Anoynne knows How do i reset the select drop-down menu after each iteration, cuz when the bot moves to next one and trys to add the options again, then it shows an error that the option already exists
Ill show the error once I reach home
how to i add a path for an image as a thumbnail url?
theres a folder called assets and inside that theres an image called image.png
does url="/assets/img.png" work?@stone palm
it doesnt
@stone palm i have an alternate way for that, upload image to a random discord dm or server then copy that media link and paste in url
thats a much longer and indirect way to do it
True maybe wait till someone knows it
@stone palm```py
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)
thanks
noring exception in command calculate:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\user\Documents\calculator\main.py", line 93, in calculate
invite = await guild.channels[0].create_invite
TypeError: object method can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: object method can't be used in 'await' expression
if sign != "A" or sign != "D" or sign != "S" or sign != "M" or sign != "a" or sign != "d" or sign != "s" or sign != "m" :
guild = bot.get_guild(ctx.guild.id)
invite = await guild.channels[0].create_invite
print(Fore.RED + f"Unsuccessfully calculated for {ctx.author} in {ctx.guild.name} server !")
logsua = bot.get_channel(config['logs_users_actions'])
await logsua.send(embed = discord.Embed(title = f"",
description = f"\๐ก ใป Bot unsuccessfully calculated for `{ctx.author}` in [`{ctx.guild.name}`]({invite}) server !",
color = 0x759fff))
huh ?
if sign != "A" or sign != "D" or sign != "S" or sign != "M" or sign != "a" or sign != "d" or sign != "s" or sign != "m" :
``` ==
```py
if sign.lower() not in "adsm":
Is there any way i can get guild preview with guild id?
invite = await guild.channels[0].create_invite()
It's a function
oh yeah
Preview?
i am getting
TypeError: 'function' object is not subscriptable
!e
def func(): ...
func[0]
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | func[0]
004 | ~~~~^^^
005 | TypeError: 'function' object is not subscriptable

I think this hasn't been added to the api wrapper yet.
You can make a raw request tough
Yea I'll
@cloud dawn ```py
Ignoring exception in command calculate:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\user\Documents\calculator\main.py", line 93, in calculate
invite = await guild.channels[0].create_invite()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1244, in create_invite
data = await self._state.http.create_invite(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 367, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel
nvm i just put 1 instead of 0
it worked tysm
TypeError: vouchbtn.init() missing 1 required positional argument: 'data'
class disbot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def setup_hook(self) -> None:
self.add_view(vouchbtn())
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
vouchbtn() you haven't passed the parameter data.
i think you can decorate your error handler with @<command_name>.error
not really working for a cog
also if its possible i would like to handle all the errors from the tree with a single function
That's how I do it
What's not working about it
is there any way to catch all exception in the command tree in a single place ?
Pycord has trees?
Hey there,
having some problems getting started with slash commands:
Do I have to sync anything?
What am I missing?
import discord
from discord import app_commands
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Cog-Loaded: Ping")
@app_commands.command(name="ping", description="returns the measured latency")
async def pong(self, interaction: discord.Interaction):
await interaction.response.send_message("Pong!")
# Setup function
async def setup(bot):
await bot.add_cog(ping(bot))```
Where is the slash command?
oh hold on
in your ||a ๐ธ ๐ธ|| hi zeffo
Guys I need help
When I type the bot command, it doesn't work
Could you be more precise? What's not working?
how can i get inviter in a on_member_join(member) event ?
I am typing the command but it doesn't do anything
are you listening to the on_message event somewhere?
@glad cradle ๐น
No, I don't know anything about this event
@glad cradle
yes
AFAIK there's no way with the exposed Api, you need to track invites and check what invite has undergone an increase in its uses
can you share your code
oh ok
k np
anyone ?
I put it here or send it to you in private @glad cradle
you could use
wait how was it
!d discord.ext.commands.Cog.cog_check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
this
here if possible
remove your token
k
interesting thanks
import discord
from discord.ext import commands
from PIL import Image, ImageDraw, ImageFont
import requests # ุฅุถุงูุฉ ูุฐุง ุงูุณุทุฑ ูุงุณุชูุฑุงุฏ ุงูู
ูุชุจุฉ "requests"
intents = discord.Intents.default()
intents.members = True # ุชู
ููู ุงูุจูุช ู
ู ูุฑุงุกุฉ ูุงุฆู
ุฉ ุงูุฃุนุถุงุก ูู ุงูุฎุงุฏู
ุชู ุงุฎุชุตุงุฑ ุงูููุฏ ููุชุฑููุฒ ุนูู ุงูุฌุฒุก ุงูู ุญุชูู ุนูู ุงูุฎุทุฃ
client = commands.Bot(command_prefix='$', intents=intents)
ุงูุฃู ุฑ ุงูุฌุฏูุฏ
@client.command(help="Draw text on your profile picture.")
async def draw(ctx, text):
# ุชุญู
ูู ุงูุตูุฑุฉ ุงูุดุฎุตูุฉ
avatar_url = ctx.author.avatar_url
avatar_image = Image.open(requests.get(avatar_url, stream=True).raw).convert('RGBA')
# ุฅุถุงูุฉ ุงููุต ุนูู ุงูุตูุฑุฉ
draw = ImageDraw.Draw(avatar_image)
font = ImageFont.truetype('arial.ttf', size=32)
draw.text((50, 50), text, fill=(255, 255, 255, 255), font=font)
# ุชุญููู ุงูุตูุฑุฉ ุฅูู ู
ูู ูุฅุฑุณุงููุง ุนูู Discord
avatar_image.save('edited_avatar.png')
await ctx.send(file=discord.File('edited_avatar.png'))
client.run('token')
you're welcome
you're missing the message_content intent
enable it doing intents.message_content = True after intents.members
maybe you need to explicitly specify the path to the ffmpeg exe
how would i set a cog listener on cooldown ?
commands.cooldown doesnt work does it
try enabling logging to see if something unexpected occurs
AFAIK the library doesn't have such a thing, you somehow need to keep track of them yourself and dispatch a custom event ("cooldown"), later you will be able to listen to "on_cooldown" and do things
btw shouldn't be that difficult
you can follow this guide https://discordpy.readthedocs.io/en/latest/logging.html
guys I just read the docs and in that I got to know there are two different commands
commands.Bot and the other is discord.Client
I just wanted to know how I can combine both of them
commands.Bot is a subclass of Client so every feature of Client is available in commands.Bot
You really shouldn't combine both of them
commands.Bot is a superset of discord.Client so bot has everything client does and more
I predicted you 
mh could you share the full logs
there's an exception
send it
and could you also share the affected code?
class PersistentViewBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)
async def setup_hook(self) -> None:
self.add_view(PersistentView())
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
can i use persistent button without doing this?
cuz my Persistentview() requires an arguement
mh is the YouTube link valid?
what's the best practice for storing a bot token for discord.py
GOod question
store the unix timestamp as a real date, store the bot ID somewhere else, and store the discord encryption key part thingy somewhere safe, then fetch everything from all the places, do the stuff to make it a bot token and then use it
just put it in an environment variable
doesn't even have to be a .env file
how do i make it so only the author of the command can see the response
yeah, you can use a .py file too
make sure to add that file to .gitignore
use a bin file
ah and import it?
ephemeral messages but it's only possible with modals, views, and slash commands
No fun then
yeah
thank you
how can i use a PIL.Image.Image as an image in discord.Embed im using dpy
image_bytes = io.BytesIO()
image.save(image_bytes, format="PNG")
image_bytes.seek(0)
file = discord.File(image_bytes)
source: https://stackoverflow.com/questions/60006794/send-image-from-memory
Guys How can I register slash commands in every server?
Don't specify a guild
i made a ticket system but i wanna add !close to close a ticket but idk how
can u help me?
i made a ticket system but i wanna add !close to close a ticket but idk how
yeah
but what if he writes it in another channel and deletes another chnnel?
i dont want code like that
yeah
Lemme send u my whole code
async def ticketcallback(interaction):
guild = interaction.guild
role = discord.utils.get(guild.roles, name ="interviews")
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
role: discord.PermissionOverwrite(view_channel=True)
}
select = Select(options=[
discord.SelectOption(label="Help Ticket", value="01", emoji="โ๏ธ", description="This will open a help ticket"),
discord.SelectOption(label="Application ticket", value="02", emoji="๐", description="This will open an application ticket")
])
async def my_callback(interaction):
if select.values[0] == "01":
category = discord.utils.get(guild.categories, name="Tickets")
channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrites)
await interaction.response.send_message(f"Created ticket - <#{channel.id}>")
await channel.send("Geia sas, pws mporw na sas boithisw?")
elif select.values[0] == "02":
category = discord.utils.get(guild.categories, name="Application tickets")
channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrites)
await interaction.response.send_message(f"Created ticket - <#{channel.id}>")
await channel.send("Geia sas, pws mporw na sas boithisw?")
select.callback = my_callback
view = View(timeout=None)
view.add_item(select)
await interaction.response.send_message("Choose an option below", view=view, ephemeral = True)
@bot.command()
async def ticket(ctx):
button = Button(label="๐ค Open a ticket", style=discord.ButtonStyle.green)
button.callback = ticketcallback
view = View(timeout=None)
view.add_item(button)
await ctx.send("Open a ticket below", view=view)
I'm not sure what's happening, can you try to use discord.FFmpegPCMAudio
Do u understand the code @slate swan
class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
Warning
You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
wasn't you using FFmpegOpusAudio
Snipy can y help me with aarav
hi what's the problem
i made a ticket system but i wanna add !close to close a ticket but idk how
what audio source are you using? FFmpegPCMAudio or FFmpegOpusAudio?
then
you're passing them here
you don't need to pass them if their value is equal to the default ones
just leave url
then Idk sorry
lemme try it
oh i see
bc the code is a bit changed
lemme send u the updated one
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the 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.
can somone help me to make a count member whit cogs
can somone help me to make a count member whit cogs
k
where should i put this
alr lemme try
but the channel everytime changes
the channel is named based on the user's name
i know
but theres a different channel everytime
so the id changes
can somone help me to make a count member whit cogs
Demn
just save it to a database, this list won't save after the bot restarts anyway
Mudkip still here
instead of making "leaf: the most advanced discord bot"
ahh
Hm
how do i do slash commands on discord.py
anyone knows how to reset the selection options before its called so you dont get
In components.0.components.0.options.5: The specified option value is already used
error
Im trying to make an interest command where for every single person in the database it adds on like 50 coins per hour
how would i create this hourly task
Hi guys, can you advise on the best way to handle permissions, cooldowns, and channels where commands can be used for a Discord bot? Should I use a database or some other method?
!d discord.ext.tasks.loop
@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").
@cloud dawn could you help me for that error ?
These are all supported via discord.py quite easily
You shouldn't need a database for it
As a beginner in programming, I am currently writing a bot on disnake, and I know that there are cooldowns and other features. But how can I make certain roles bypass the cooldowns set by the disnake library?
Iirc you'd have to create a custom cooldown (see https://github.com/Rapptz/discord.py/pull/6691)
so whats the best way to do it? How and where to store for each team a new participant with time?
Don't use that
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
and for pycord ?
could gimme a slash command syntax with embed and link button in it ?

i do not know pycord sorry
no, just with discord.py
class MyView(discord.ui.View):
def __init__(self):
self.add_item(discord.ui.Button(style=discord.ButtonStyle.link, url="https://example.com", label="Example"))
@app_commands.command()
async def slash_command(self) -> None:
await interaction.response.send_message(view=MyView())
oy
thanks, and how can i make 2 views ?
just make another class????
yeah i did but how can i add the view to the embed ?
in that case you want add_item instead
Hello, does anyone ever managed to run a discord bot alongside a Flask app under Cpanel?
I have, but not using cpanel
@smoky sinew hey
do you know much about raspberry pi hosting
I know a bit about networking and i know i would need to setup a firewall and/or a proxie?
to host a discord bot?
yes
realistically, no.
no what? no firewall or proxy?
either
oh why?
why would you need it?
well, a reverse proxy can help improve the performance of your bot by caching frequently accessed data and load balancing incoming traffic
but realistically no ones going to try get gain unauthorized access to your bot
idk if im correct but i thought a proxy is basically a middle man between the client and server (my pi)
you are correct
would my home network take care of dos attacks
and my pi wont need to worry
if there was any
alsomexxx, no one can get your ip from your discord bot
but if you are worried about this, your typical home network will not take care of DOS attacks
ratelimits
what will
oh yeah
okay, someone spamming your commands wont even be flagged by your network provider as it is coming from your own network
best course of action is to set up ratelimits if thats something you are really concerned about
no need to say sorry brother, here to help
also, would 1gb of ram be alright
I've had about 300 people spamming my bot during an event and while the bot sometimes slowed down my internet never did
for a small scale bot, yes
hard to estimate but off of my experience, 4gb of ram it could handle anywhere between 1-2 commands a second
without a delay
what PI do you have? (i own the pi 4 b)
2 b
I was on a budget
im using a wireless node and connecting a ethernet between that and my pi
well, it will depend on various factors, such as the complexity of your bots commands, the number of users interacting with your bot, and the load on your raspberry pi's cpu and memory (if theres other stuff running on it)
the rasp pi 2b can handle (i would say) a moderate level of traffic for a simple Discord bot with basic commands. However, if your bot is handling a large number of commands per second or processing complex tasks, you may experience performance issues.
then you should have no worries, i would suggest monitoring the work load on your cpu and memory while it is running
it wont need any type of cooling would it?
it'll most definitely get hot. person use with my Pi it reaches high degrees but you can buy a cheap fan if you're worried about it getting too hot
raspberry pi fans are fairly cheap
no worries, give me a ping if you need anything else!
will do, thank you
good luck
how to timestamp for embed?
datetime.datetime.utcnow()
embed = discord.Embed(description=f"{ctx.user} feldobta az รฉrmรฉt!", color=discord.Color.blue(), timestamp=datetime.datetime.utcnow())```
this?
@maiden fable
yes
!d discord.User.banner
property banner```
Returns the userโs banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
you need to do fetch_user first
@silk kestrel
thank you
Guys is there any glitch going on for discord.py and py-cord?
I want to make a leaderboard but it only selects people in that server
how would i create this using aiosqlite
do you want to make a global leaderboard or a guild leaderboard
guild
global one i made
but guild one im strugglign with since how do i make it only extract data from people that are in the guild specified
then what's the problem
this
im struggling with making guild leaderboard
specific to people in that server
are you storing the user ids?
you already have the ids of the members that are in that guild
yes
yes
but how do i make it so instead of just getting top 10 people in the database
the people it orders are the people that are in the server
!d discord.Guild.members
property members```
A list of members that belong to this guild.
ty but i know that
make a sequence of all the user ids in the server
users = [us.id for us in interaction.guild.members]
and just use a WHERE clause
so WHERE user = ?
IN
oh
users = [us.id for us in interaction.guild.members]
async with client.db.cursor() as cursor:
await cursor.execute("SELECT money, user FROM banks WHERE user IN ? ORDER BY money DESC LIMIT 10",(users,))
so smt like this?
this does not work
is there a guild id for users in the table?
"abc" + (f"type: {type.name}" if type is not None else "")
is this possible?
What
f"abc type: {type.name if type else ''}"
try
string = f"SELECT money, user FROM banks WHERE user IN {tuple(user)} ORDER BY money DESC LIMIT 10"
await cursor.execute(string)
WHERE guild_id = ...
i think injection might not be allowed with in operation like that
is that a thing?
it would be easier if there was a guild id column
problem with that is
i want data to be same across all servers
this is a server leader board i assume?
yes
try this
GLobal one i made but server is difficult
you want the data to be the same but the leaderboard displays different things per guild??
remember that values need to be like this
user in (1, 2, 3, 4) order by
oh you want to filter it for members that are in the current server
also u could just do a for loop and match too i suppose but i think f string is a valid use case here
yes
basically thats it
i tried that and i get OperationalError
Send the whole traceback
print that statement once

i think tuple might be adding a extra comma or something which might make it an invalid statement
what do u get when u print the statement
which statement?
print the f string
also when i print the tuple
ah ah, me sniffing network comunications and sending sql injections in ids (totally not possible)
there is extra comma at end
better just make a table to map user id and guild id
how u gonna
u cant inject at that position... unless u hack discord api
i said
remove it
totally not possible
mad asher

btw even if it's possible from a network perspective the library would error since it tries to convert discord ids to int
class Prot(discord.ui.View):
response1=None
list_result=[]
self.users=users
def __init__(self, users:list):
super().__init__(timeout=10)
async def selected(self, interaction:discord.Interaction, selected:discord.ui.Select):
How do i acesss the users list inside the selected function?
self.users?
Doesn't exist, you didn't define it
What
defined
Hi guys! Trying to finish my discord bot. Is there now a way to add buttons to do specific commands like copy-to-clipboard the targeted text?
Never heard of ability to copy to clipboard via button in discord
Or has there been a way now to use pyperclip with discord?
How are you going to use that on server side
๐ซ
I'm new with python and discord integration D:
That's simple logic
How are you going to use clipboard of user's computer with your bot's server
There's no way unless you tell discord client to do so which you can't
Uh yeah maybe not that simple for beginner but still
You are building server side application, not a client app
You cannot interact with user's computer, you can only send data to client (or to discord servers and then they send it to client) and it decides what to do with that
Can someone show me the examples of cogs in discord py v2
It's exactly the same
Maybe just a little different that in v2 the add cog meth is async
But that's it
Guys How Get Person Role In Discord Server In Discord bot like interactive.role?
oh alright
when i restart my bot my buttons doesnt work how to fix it?
hey guys so im making a discord bot with the package dhooks
and when i do @lament oaron'e it works as should but when i do @(role) it doesnt notify the people in the role it just types @(role)
code:
webhook.send("@premium")
You either get all roles or top role
member.roles and member.top_role correspondingly
top role
so interactive.top_role?
What is interactive
As far as it's an instance of discord.Member sure
To my knowledge there's no list type in sqlite
If this is your question (not sure why you submitted image tho) the solution is to have individual row for each user ID โ item ID pair
how to make persistent button?
which decorator to use in cogs for creating a slash command
class UserProfile(commands.Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
//some decorator
async def profile(self, interaction: discord.Interaction):
await interaction.response.send_message('ok')
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
@slate swan
thanks a lot Asher!
What should I make my bot do? ๐ค
here i have id of players, how can i add this id to other class
i don't understand the problem here
i did copy and past from website and put my own bot token
huh ?
What is discord.default_permissions?
Admin
@default_permissions(administrator=True)
Ok but that's not part of discord
it works in my hoster
Recheck it's location
but not in replit bcz i'm outside
discord.default_permissions doesn't exist so it's not going to work anywhere
Check the docs, make sure it's part of discord and not discord.app_commands or something else
Looks like one of your folders is called S'
Which is causing an issue
Run the code via the py command instead of through the IDE
can anyone help me making a discord bot maybe 100- 200 lines of code only ๐ญ๐ญ๐ญ๐ค๐ค๐ค๐ค
how ?
We don't allow recruiting/ hiring here.
py bot.py
so i have the message intent enabled for my bot but im not receiving message.content... i am using this portion of code to test this
@client.event
async def on_message(message):
if message.author == client.user:
print(f'{message.channel.name} + {message.author.name} + {message.content}')
return
if message.content.startswith('$hello'):
await message.channel.send(f'Hello {message.author.name}!')
if message.content.startswith('$dead'):
await message.channel.send(f'you died {message.author.name}!')
How have you enabled it?
You have to enable it in code too
yes there as well with this
intents.messages = True
intents.message_content = True
intents.typing = True```
that is a excellent question
i was going off the quickstart guide for discord.py https://discordpy.readthedocs.io/en/stable/quickstart.html
where/how would i use the intents variables?
you pass it to intents kwarg of discord.Client




