#discord-bots
1 messages · Page 345 of 1
so this should work ```py
for reaction in message.reactions:
if not reaction.count:
msg = await star_channel.fetch_message(em_id) # type:ignore
await msg.delete()
(
await self.bot.db.execute(
"DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
guild.id,
em_id,
)
if self.bot.db and guild
else None
)
elif reaction.count < star_count:
if not self_star:
if message.author == payload.member:
return await message.remove_reaction(payload.emoji, payload.member) # type: ignore
star_embed = await star_channel.fetch_message(em_id) # type: ignore
await star_embed.edit(content=f"⭐ **{reaction.count}** | {channel.mention}") # type: ignore
?
thats still basically the same
if the last reaction was removed, there won't be any ⭐ reaction listed in message.reactions
you can only tell if it has 0 stars by seeing if a reaction with that emoji exists
but your for loop still assumes that the reaction object exists
once the last reaction is removed, message.reactions will return an empty list [], so do you get what happens when your for-loop tries to iterate over that list?
if message.author.bot or payload.emoji.name != "⭐" or not message.reactions:
return
``` so this fixed that
dont you want to delete the starboard message once the reaction's gone though?
hm, i can do that before that return
but this is what u were saying right?
if this any of this is true, it exits
^ this point stands too, technically the message can have other reactions besides a ⭐ so you want to be mindful of that
ahh
wait but its payload.emoji.name != ⭐
if its only star, it will work
message.reactions can still return other emojis
or i can put that as another if statement
if message.author.bot or payload.emoji.name != "⭐":
return
if not message.reactions:
msg = await star_channel.fetch_message(em_id) # type:ignore
await msg.delete()
(
await self.bot.db.execute(
"DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
guild.id,
em_id,
)
if self.bot.db and guild
else None
)
return
if you had a message with two reactions, 🤖 and ⭐, and the ⭐ gets removed, you are still left with 🤖 so message.reactions will not be an empty list even though there are 0 stars
so what'd u suggest
this
find the reaction object for ⭐, if it doesn't exist then you know there are 0 stars, if it does exist then there is at least 1 user that still has a star
emoji = discord.utils.get(message.reactions, emoji="⭐")
if message.author.bot or not emoji:
return
good?
do you still want to delete the starboard message after 0 stars?
yeah
@Cog.listener(name="on_raw_reaction_remove")
async def starboard_reaction_remove(self, payload: discord.RawReactionActionEvent):
guild = self.bot.get_guild(payload.guild_id) if payload.guild_id else None
channel = guild.get_channel(payload.channel_id) if guild else None
message = await channel.fetch_message(payload.message_id) # type: ignore
emoji = discord.utils.get(message.reactions, emoji="⭐")
if message.author.bot or not emoji:
return
em_id = (
await self.bot.db.fetchval(
"SELECT bot_msg_id FROM star_info WHERE guild_id=$1 AND user_msg_id=$2",
guild.id,
payload.message_id,
)
if self.bot.db and guild
else None
)
if not message.reactions:
msg = await star_channel.fetch_message(em_id) # type:ignore
await msg.delete()
(
await self.bot.db.execute(
"DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
guild.id,
em_id,
)
if self.bot.db and guild
else None
)
return
then dont return early yet
you can replace the not message.reactions condition with your emoji check for that
if not emoji?
sure?
so i can replace all occurences of message.reactions with emoji ?
inside an app commands group, how would you do a subgroup?
i believe you use the parent= argument, i.e. ```py
foo = app_commands.Group(name="foo")
bar = app_commands.Group(name="bar", parent=foo)
@bar.command()
async def baz(interaction):
...```
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
btw, this should work right?
https://paste.pythondiscord.com/T3QA
your if message.author.bot or not emoji: return line is going to prevent it from reaching the message deletion
ok ty
if message.author.bot or not emoji:
#return
if not emoji:
msg = await star_channel.fetch_message(em_id) # type:ignore
await msg.delete()
(
await self.bot.db.execute(
"DELETE FROM star_info WHERE guild_id=$1 AND bot_msg_id=$2",
guild.id,
em_id,
)
if self.bot.db and guild
else None
)
return
return
ping me when ur back
How do I deploy changes with Docker? Do I need to stop the container, remove it, rebuild it with the new .py code, and then run to apply the changes?
I mean I could create a shell script
#!/bin/bash
docker stop blitzcrank
wait
docker rm blitzcrank
wait
docker rmi blitzcrank
wait
docker build -t blitzcrank .
wait
docker run -d --name blitzcrank --restart always -t blitzcrank```
And run it in the current directory
Or is there any better way to do it?
Given this function async def _alarm(interaction, hour: int = -1, min: int = -1):
Can I specify that I either need no arguments or both hour and min?
(discordpy command)
I guess basically an object or tuple argument in the function signature
like both must be specified at the same time? you can check in the function once they've used the command but you can't restrict it client-side, for the latter you might prefer separating them into two commands, like /alarm get and /alarm set <hour> <minute>
Ah okay. I was hoping there was a way to say "Either no argument to trigger one overload, or these 2 arguments if you need the other version"
But if that isn't possible I'll have to rethink
Using this from discord.ext tasks only runs once. I was under the impression it would run every 0.1 seconds?
@tasks.loop(seconds=0.1)
async def _check_alarms_loop():
print('tick')
Ah I got it. Forgot to call start
Is it possible to get some sort of context from a Client? (client = discord.Client(intents=intents))
Or do I have to manually go through the guild list and channel list to find the right channel to send to?
I don't have a context object in my thread, but I need to send a message to my channel.
in relation to your alarm system? i suggest storing the channel IDs with each alarm in a dictionary and/or database so you can use it to retrieve the channel object to send to
What if the resulting message that comes from that alarm should be sent in a different channel than where it was created?
Do I just designate a channel to that and save the channel with that id?
can you use context menus in a cog?
My problem currently, is that I don't know how to include a context with this looping task:
@tasks.loop(seconds=0.5)
async def _check_alarms_loop():
Because that looping task will eventually trigger a function that requires a context of some kind to send a message
async def _broadcast_alarm(user_id, ctx = None):
if isinstance(ctx, discord.interactions.Interaction):
await ctx.channel.send(<message>)
await ctx.response.send_message('', ephemeral=True, delete_after=0.01)
else:
await ctx.channel.send(<message>)
kind of? it has to be manually added/removed
https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458
technically i guess you could store contexts, but i recommend
oops
i recommend refactoring it so you only need the timestamp, channel ID, and message content for each alarm
What would the timestamp do for me?
also interactions have to be responded to within 3s and the followup webhook it provides will only last for 15min so they won't be of much use for your long-running alarms
keep a list of the alarms planned to occur, then in a loop you can check which alarms are ready to be sent
I have a bunch of datetimes for that. Works as expected.
My biggest issue is how I get a context. Because the background task that checks every alarm and whether they should trigger or not has no context to send messages through
So I'm unsure how your suggestion would help there as I would still need a context
the channel ID can be used with the bot object to retrieve the channel object that'll let you send messages to
i guess you could store a context object in said list, but designing your code around a context makes it difficult to make your alarms persistent in a database
I tried making a bot instead of a client.
The get_guild() function returned an empty channel list when I then called get_channel() or when trying to iterate over guild.channels
did you not enable the guilds intent?
I did online, but I probably forgot in code.
should do it like this?
intents = discord.Intents(messages=True, guild=True)
its not a privileged intent so you dont need to enable it in the dashboard
for simplicity you can use discord.Intents.default() and then tack on whatever privileged intents you do need, like: py intents = discord.Intents.default() intents.message_content = True but if you want to be explicit, you should be careful about which intents you leave out because some like guilds= affect many features of dpy
But so for this particluar issue, I do need guilds right?
yes
Okay.
https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds
This also corresponds to the following attributes and classes in terms of cache:
Client.guildsGuildand all its attributes.Client.get_channel()
...
Yeah doing the intent thing worked. Thanks @hushed galleon
I was going insane for a bit there 🥲
:incoming_envelope: :ok_hand: applied timeout to @nimble timber until <t:1709867414:f> (10 minutes) (reason: emoji spam - sent 23 emojis).
The <@&831776746206265384> have been alerted for review.
So, I wanted to know if there is a way to make a command in a discord bot with what is described below:
I'm making an rpg bot for discord using python. I want to make a command with the name "h!profile", this command will send the following message in embed:
**╭┄┄┄┄┄┄⇢ Profile ⇠┄┄┄┄┄┄╮**
**This Will Show Your Information.**
**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**
**❪ ❫ Name. . . ⇢ User**
**❪ ❫ Title. . . ⇢ Not defined**
**❪ ❫ Element. . . ⇢ Not defined**
**❪ ❫ Race. . . ⇢ Not defined**
**❪ ️ ❫ Class. . . ⇢ Not defined**
**❪ ❫ Rank. . . ⇢ Not defined**
**❪ ❫ Mastery. . . ⇢ Not defined**
**❪ ️ ❫ Cardinal Hero. . . ⇢ Not defined**
**❪ ❫ Unique Skill. . . ⇢ Not defined**
**❪ ❫ Blessing. . . ⇢ Not defined**
**❪ ❫ Curse. . . ⇢ Not defined**
**❪ ❫ Buffs/Debuffs. . . ⇢ Not defined**
**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**
**❪ ❫ HP. . . ⇢ Not defined**
**❪ ❫ Ikari. . . ⇢ Not defined**
**❪ ❫ Core. . . ⇢ Not defined**
**❪ ❫ Strength. . . ⇢ Not defined**
**❪ ❫ Physical Defense. . . ⇢ Not defined**
**❪ ❫ Magic Defense. . . ⇢ Not defined**
**❪ ❫ Speed. . . ⇢ Not defined**
**❪ ❫ Melee Weapons. . . ⇢ Not defined**
**⊱⋅ ────── ❴ • ✿ • ❵ ────── ⋅⊰**
**Read The Status System!**
**╰┄┄┄┄┄┄⇢ Status ⇠┄┄┄┄┄┄╯**
however, the "not defined" in the message will be replaced by variables, these variables will already have a defined value, for example: hp variable with a value of 5,000. These variables can be modified by the command "h!set-<variable> <user> <quantity>", example: h!set-hp roger 6,000", then when roger uses "h!perfil" it will show 6,000 instead of "5,000" or "not defined". This command can only be used by specific positions and it will only change the status of the person mentioned, that is, if roger has his hp changed to 6,000 and christian uses "h!perfil" it will show on christian's profile that he has 5,000 and roger's 6,000
what you could do is use f-strings
other than that, i am not sure what are you asking for
Okay, so I am trying to make something like DiscordGSM, but I can't find a good API that is kinda fast. The one I have rn, when a server goes offline, it takes like 30 minutes to even update.
The games I am mainly looking for are
- Unturned
- Minecraft (2009)
If there is a better way of doing this without an API please let me know!
what is DiscordGSM?
oh, but still I didn't understand your question. are you trying to see if your game server got offline?
if so, that should be easy
I am looking for a good API that will do it for me. Because the current API that I have, it doesn't refresh its data until after 30 minutes, which isn't really good.
Or I am asking if there is a way to do it without an api. Which I don't think there is.
https://paste.pythondiscord.com/DLCA
This is what I have so far, which I am using battlemetrics api.
But their api takes 30 minutes to refresh, which isn't really good because by the time it refreshes, the server would be back up, showing the server never went down, even tho it did.
this isnt really relevant to the #discord-bots channel but i would wager a guess that using that Server List endpoint might be giving you outdated results, and you should try the Server Info endpoint specifically meant for getting info about a single server
i use that endpoint for my bot's arma server status and it updates fairly quickly, at least quick enough for 1 minute refreshes
Is there any way to edit the "about me" section using discord.py?
without discord.py??
yes
How?
go to the bot page on discord.com/developers and change the "description" of the bot on the General tab
ah
I understand, but this method is manual. I want to automate it with code.
oh ok thank you
for s in self.bot.guilds:
embed=discord.Embed(title="Guild that are bot is join", description=f"""**Server name** :- {c}
**Server ID** :- {c.id}
**Server Owner** :- {c.owner}""")
await ctx.send(embed=embed)```
Why this not working
This is not sending anything
ctx is not defined
It's already
I changed the description of embed then it's working
?
I didn't send full code
No problem sending any where
@vestal acorn
I found that
@vestal acorn
oh
Mm
I see
Okay ty. Also if you don't mind me asking, how is it not relevant to #discord-bots? I thought we could ask anything about bots here. Maybe I miss understood lol
Not to be rude either, just truly asking ^^
Cuz it ain't related to the discords api
from discord.ext import commands
from discord import Intents
intents = discord.Intents.default()
intents.message_content = True
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.tree.sync()
@bot.tree.command(name="hello", description="Says hello to the user")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(f"Hello, {interaction.user.display_name}!")
bot.run('')```
Can someone explain why my bots slash commands won't show up?
hello all, where you using server to discord-bot? Are on cloud or your computer?
Self-host
You can try reading this if it helps
i want to make a python bot with discord.py, if i want to make a lot of commands do i need to make them all on the same file?
If imported intents directly then why usin discord.Intents instead of Intents.default()
No
tell me more
You can use cogs for clarifying your cmds
what is a cog?
This is not a Modmail thread.
Hmm
Cogs are like you can make a new file and make a class and under the class you can define you CMDs
True
And also you have to add that file in your bot main file by using
await bot.load_extension("cogs file path")
i need help
Yes
Do yk what I have to do to make my bot support commands
you don't need discord_components
Just use buttons and selects from discord.ui, which is already implemented in discord module
do I then from discord.ui import Button, etc?
you need to use it in a certain way, I recommend you UwU videos
https://www.youtube.com/watch?v=kBsemdGRglQ&pp=ygUTdXd1IGRpc2NvcmQgYnV0dG9ucw%3D%3D
In this video I will be showing you types of button and their functions such as timeout, cooldown, and click authorization in discord.py v2.0+. Alongside with a simple quiz/trivia command using buttons.
examples ^
Hello, I am trying to get my discord bot to send out a command after a certain amount of time that another command has happened.
async def handleCheckin(interaction):
await asyncio.sleep(600)
global isCheckinActive
if isCheckinActive:
isCheckinActive = False
await getPreviousMessageAndDelete()
await volunteercheck(interaction)
however when I tried to do it that way, it spits out the error, "'Command' object is not callable"
(code for volunteercheck)
async def volunteercheck(interaction):
view = volunteerButtons()
await interaction.response.send_message('The Volunteer check has started! You have 10 minutes to volunteer if you wish to sit out', view = view)
Could someone help me with this?
How can i have an appcommand argument perform a lookup on disk with an sql database for a big dataset?
is there any "slash" only package ?
Typehint as string and do the logic.
No not really any I'd know of, best method in discord.py would be to use Client object and work from there.
Extensions and reloading, loading, unloading are pretty doable things to re-create and worth it in my opinion to do to get the desired behaviour.
hello
how would i be able to get any extra information inside my auto complete func
like i need to know what table i want to search in when performing the search in my autocomplete func
nevermind figured it out
Im getting this error message below
Traceback (most recent call last):
File "main.py", line 20, in <module>
Intents.messages.content = True
AttributeError: 'bool' object has no attribute 'content'
hello
"For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries."
I switched to Server Info endpoint, but it still isn't updating as fast. Ive waited like 10 minutes, the file still says the status is online
Show code
does it say the same on the battlemetrics dashboard for that server?
huh?
https://api.battlemetrics.com/servers/24191995
if you read it, the status is "online"
Server clearly offline on my end tho.
oh no wonder, battlemetrics really isn't querying it often enough
https://www.battlemetrics.com/servers/unturned/24191995
Yeah
thats what I said, which I have no clue how to up that
I mentioned the api was slow with it, so thats why I was wondering if there was another API
I did explain poorly, but I was really tired lol
well, you're looking for APIs/libraries to query the status of unturned/minecraft servers which only some people here would know about
i know there's that yellow button that lets you manually refresh, but you probably should ask in battlemetrics's discord server for a way to increase the query frequency
https://www.battlemetrics.com/contact
there's also the Server Force Update endpoint but it says that's "limited to subscribers and users who belong to the organization that owns the server if it is claimed" (not sure if that means you can use it on unclaimed servers or as a separate party from the owning organization)
(also returns 202 Accepted so it probably won't be updated immediately)
Well, if its for claimed, then I could just claim if, which would be easy to do.
oh you're using it for a server you own? should be good then
Do u know another api tho?
It is Intents.message_content
You need to invoke it in a special way. https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.invoke
Note this would be something like ctx.invoke() or interaction.invoke()
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
how can i learn to make a discord bot
hello
https://fallendeity.github.io/discord.py-masterclass/
https://github.com/Rapptz/discord.py/tree/master/examples
A hands-on guide to Discord.py
and official discord.py docs are a good place to start
u can also ask any doubts you have here
hello i currently have a bot that generates a challonge tournament link based off the people in the vc and sends it in a channel, how do i make it send an image of the challonge link?
https://api.challonge.com/v1/documents/tournaments/create
the response has a live_image_url key, use it?
What do you mean by an image of the link?
Do you have the image or ...?
Just follow the discord documentation. It's not that difficult. Also it depends on what kind of bot you want. You can make the basic one in 30 minutes
like an image of the bracket that gets generated
https://i.imgur.com/4jU1r1G.png an image of this lets say
So do you have the functionality to create the image? And you are asking how to return it in the response of discord?
i dont have a functionality to create the image
thats what i need help with
i dont know what to do to create the image
Are you coding in python?
yes
Then it has nothing to do with the discord. You need to make a function to return you with an image and call that function inside your discord bot function.
Hey guys, im looking for a discord bot that can run with discord.py. the only finctionality it needs to be able to do is log in, and post a message that the py script will generate
any ideas?
was this for me?
No
@hushed galleon
I will send you the script, remind me on Monday.
yes
What's that?
Why are you looking to use Discord as a C2 server? C2 generally implies less than legal circumstances...
Do you have videos where they explain the api?
all the videos are pretty outdated
for api docs u can look at discord devs api documentation
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1709993382:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
bot.tree.walk_commands()
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
from discord.ext import commands
import discord
import traceback
class CounterBot(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 on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
class Feedback(discord.ui.Modal, title='Feedback'):
name = discord.ui.TextInput(
label='Name',
placeholder='Your name here...',
)
feedback = discord.ui.TextInput(
label='What do you think of this new feature?',
style=discord.TextStyle.long,
placeholder='Type your feedback here...',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
traceback.print_exception(type(error), error, error.__traceback__)
class Counter(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Verify', style=discord.ButtonStyle.red)
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(Feedback())
bot = CounterBot()
@bot.command()
async def test(ctx: commands.Context):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=Counter())
bot.run('BOT TOKEN')
i want bot button dont expire
anyone?
has someone nice functions about i want to create a Security bot
classic:
- ban
- kick
- mute
- tempban
- tempmute
- captcha/verification
raid:
- detect mass join
- block any join
- detect mass join in voice channels
- block joins in voice channels
- lock every channels with an automatic backup
- disable every too big perms (admins)
these are just some ideas
thank you
you're welcome
Anyone know how to resolve when i have two choices in a list with the same name but different values they both result in the same value when selected in an app command?
choices = []
choices.append(app_commands.Choice(name="Foo", value=1))
choices.append(app_commands.Choice(name="Foo", value=2))
@bot.tree.command(name="abc", description="123")
@app_commands.choices(myarg=choices)
async def abc(ctx: discord.Interaction, myarg: int):
assert(myarg==1) # will always be triggered
``` this is basically what im doing, it will always result in `1` no matter which `Foo` i choose
File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lucia\Desktop\Bot Discord\Python\Bready Bot Totali\BreadyMC General\main.py", line 212, in ticket
await ctx.send(embed=embed, components=[select])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Context.send() got an unexpected keyword argument 'components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Context.send() got an unexpected keyword argument 'components'```
This is a keyword argument thats avaliable in some other discord.py fork but not in rapptz discord.py i assume
@civic sparrow
Hi, I was wondering if you could help me with just one thing:
Is this part of the code ok or does it need to be changed? Because it gives me an error
await
ctx.send(embed=embed, components=[select])
Then show the error
no i just said this doesnt exist in normal dpy
you need to find and use the fork that allows that
or use views like th above examples
i wouldnt use forks for some layer of abstraction and learn properly, especially since it can become desynced with the origin dpy
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
We don't help with self bots
Hoy
do you know if Im able to get a bot to blacklist a server
from joining another server
Got question I feel some of y'all might know.
ctx.author.display_name <-- Will show secondary discord user name in profile.
ctx.author.display_avatar <-- Will show discord user profile picture icon.
??? <-- Will show discord user name as seen directly in posts.
??? <-- Will show user id number.
Anybody know what the missing ones are called?
I believe that ctx.author.display_name will show the discord user name as you'd see in messages, since it accounts for nicknames. ctx.author.name returns their actual name that's on their profile. ctx.author.id for their ID
Finally. Thank, some good news.
I just used the ctx.author... well you know what, let's use Robin as example.
ctx.author = robinj#0
ctx.author.display_name = robinj
How do you get it to show the actual user name shown?!
I been trying to figure this out for months!
What is used to show "TailsTellsTales" instead of "tailstellstales" for example.
What
It is something like guild.nickname I think
Iirc
this should be author.display_name
but if this doesnt work you can try author.nick or author.name
?tag author
This is not a Modmail thread.
Hi, when I put options=options it gives me an error, why? The error is with has not been defined.
@discord.ui.button(label = "Quit", style = discord.ButtonStyle.danger)
async def quit(self, interaction: discord.Interaction, button: discord.ui.Button):
if await self.check(interaction):
for child in self.children:
child.disabled = True
self.stop()``` am i missing something here?
You should edit the message after that you disable the children.
You haven't defined options before. Can you show the full code?
What's wrong with it? It's not disabling the buttons?
If so, you'd have to edit the message with the view again to update the buttons' states
Yeah or in DMs.
import discord
from typing import Union
class Pagination(discord.ui.View):
def __init__(self,
interaction: discord.Interaction,
messages: Union[list, tuple],
embed_title: str,
embed_color: discord.Color = discord.Color.default()):
super().__init__()
self.interaction = interaction
self.messages = messages
self.embed_title = embed_title
self.embed_color = embed_color
self.current_page = 0
async def check(self, interaction):
if interaction.user == self.interaction.user:
return True
else:
await interaction.response.send_message(
embed = discord.Embed(description = ":x: You cannot interact with this message",
color = discord.Color.red()))
def update_message(self):
embed = discord.Embed(title = self.embed_title,
color = self.embed_color,
description = f"Page {self.current_page + 1} / {len(self.messages) + 1}\n\n{self.messages[self.current_page]}")
return embed
@discord.ui.Button(label = 'Next')
async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
if await self.check(interaction):
if self.current_page == len(self.messages):
self.current_page = 0
self.update_message()
else:
self.current_page += 1
self.update_message()``` why am i getting `Button` object not callable?
Which line?
@discord.ui.Button(label = 'Next')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Button' object is not callable
wait im an idiot 😭
help me
@discord.ui.button(label = 'Next')
.bm Security bot command suggestions
hi guys , i have been studying python and i know the basic , but i want to get the things to the next level , someone can gie me advices ?<3
get to know the fundamentals like object oriented, data structure, sorting algorithm, dbms
.topic
hello . i have question. im still learning and trying to make macro bot, for few aplication on same time, did anyone know how to inject 1 script to many aplication
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.components: Must be between 1 and 5 in length. why could i be getting this in a modal?
i have one input 😭
what does your code look like? it might getting duplicated unintentionally
class GoToPage(discord.ui.Modal, title = "Go To Page"):
def __init__(self, pagination):
super().__init__(timeout=None)
self.pagination = pagination
self.page_input = discord.ui.TextInput(style = discord.TextStyle.short, label = "Enter a page", placeholder = f"Enter page number")```
It is this and then I handle the input underneath
oh, you haven't added the text input
huh?
its like views, if you create a button inside init then you need to call self.add_item(component) to add it
though for modals i recommend defining them as class attributes so its automatically added
i.e. ```py
class MyModal(discord.ui.Modal, title="..."):
my_input = discord.ui.TextInput(...)
async def on_submit(self, interaction):
await interaction.response.send_message(f"You submitted: {self.my_input.value}")```
so like this should work self.page_input = self.add_item(discord.ui.TextInput(style = discord.TextStyle.short, label = "Enter a page", placeholder = f"Enter page number"))
err, not in the way you think it will
oh its because i need to be accessing the self
that technically adds it, but add_item always returns None so self.page_input won't actually contain the text input
oh
i'd just add it on a separate line, as in: py self.page_input = discord.TextInput(...) self.add_item(self.page_input)
oh thank you that works
how can i get my bots message id after using py await interaction.response.send_message(embed=em, view=view)
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
thanks
How do I add a description to arguments?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
thanks
Trying to force a layout like this by entering a fake 'release date' field within the value of 'length'.
However, if you look closely at the images below you can see bold characters are a tiny bit different from actual field names. Is this as close as I can get? or is there a different way to approach this?
If it's too hard to see, the fake field name is slightly thicker than the real field name
Hello dear community, I need your help. How can I have the database retrieve the name and then insert it here?
options = [
discord.SelectOption(label="test", emoji=":ticket:"),
]```
I have everything in the database but I don't know how to transfer the names into the option
what db are you using?
class TicketDB(ezcord.DBHandler):
def __init__(self):
super().__init__("db/ticket.db")
async def setup(self):
await self.execute(
"""CREATE TABLE IF NOT EXISTS ticket(
server_id INTEGER PRIMARY KEY,
category_id INTEGER DEFAULT 0,
teamrole_id INTEGER DEFAULT 0,
logs_channel_id INTEGER DEFAULT 0,
ticket_channel_id INTEGER DEFAULT 0,
set_name_count INTEGER DEFAULT 0,
panel_name TEXT DEFAULT NULL
)"""
)
async def set_category(self, server_id, category_id):
await self.execute(
"INSERT INTO ticket (server_id, category_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET category_id = ?",
(server_id, category_id, category_id)
)
async def get_category(self, server_id):
return await self.one("SELECT category_id FROM ticket WHERE server_id = ?", (server_id,))
async def set_teamrole(self, server_id, teamrole_id):
await self.execute(
"INSERT INTO ticket (server_id, teamrole_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET teamrole_id = ?",
(server_id, teamrole_id, teamrole_id)
)
async def get_teamrole(self, server_id):
return await self.one("SELECT teamrole_id FROM ticket WHERE server_id = ?", (server_id,))
async def set_logs_channel(self, server_id, logs_channel_id):
await self.execute(
"INSERT INTO ticket (server_id, logs_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET logs_channel_id = ?",
(server_id, logs_channel_id, logs_channel_id)
)
async def get_logs_channel(self, server_id):
return await self.one("SELECT logs_channel_id FROM ticket WHERE server_id = ?", (server_id,))
async def set_ticket_channel(self, server_id, ticket_channel_id):
await self.execute(
"INSERT INTO ticket (server_id, ticket_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET ticket_channel_id = ?",
(server_id, ticket_channel_id, ticket_channel_id)
)
async def get_ticket_channel(self, server_id):
return await self.one("SELECT ticket_channel_id FROM ticket WHERE server_id = ?", (server_id,))
async def get_press_count(self, server_id):
result = await self.one("SELECT set_name_count FROM ticket WHERE server_id = ?", (server_id,))
return result if result is not None else 0
async def increment_press_count(self, server_id):
current_count = await self.get_press_count(server_id)
new_count = current_count + 1
await self.execute("UPDATE ticket SET set_name_count = ? WHERE server_id = ?", (new_count, server_id))
async def set_panel_name(self, server_id, panel_name):
await self.execute(
"UPDATE ticket SET panel_name = ? WHERE server_id = ?",
(panel_name, server_id)
)
async def get_panel_name(self, server_id):
return await self.one("SELECT panel_name FROM ticket WHERE server_id = ?", (server_id,))
db = TicketDB()```
generally you add your own parameters to the View/Select constructor and then pass whatever data it needs to produce the desired options, for example: ```py
class ToyView(discord.ui.View):
def init(self, toys):
super().init()
self.toy_select.options = [
discord.SelectOption(label=toy, ...)
for toy in toys
]
@discord.ui.select()
async def toy_select(self, interaction, select):
...
Fetch the data from your database then pass it to your view:
toys = await db.get_toys()
view = ToyView(toys)```
ah thx
help
Anyone know how to make data save even when the bot turns off?
Does anybody know how to do this: I saw a bot in a different server, and i ran a slash command. I didnt have permission and it sent an error message, not customised but looks like a default message from discord. Could this have been a glitch and I shouldnt have been able to run it in the server integrations?
What type of data?
Profiles. I've got a economy bot and how do I make it save their balance and what items they own.
You could either use a .json file (not recomended), or a database such as MongoDB
im using sqlite3 is that a database?
yes
that will save when the bot is off
just make sure you connect to the database before trying to retrieve data
What do you mean connect
It doesn't seem to work maybe im doing it wrong?
well because storing data in anything other than variables in the source code should stay when you stop running the code. I don't use SQL, I use Mongo so i'm not too sure, but I know when done correctly all data will stay in the database. Sorry for not being able to help
!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.
i really cant code that good
can i send to you and you maybe do it
No cause we are here to help you not code for you
did you save your code before running it? the code looks fine apart from defining multiple discord clients for some reason.
by the way, you should probably reset your bot token for Certified#5462 if you have not already because it was partially included in your paste
I resetted it before i sent it dw
it might be an issue with get_profile, which appears to override the argument variable user_id with another value. but from what i can tell there is no undefined user_id variable in the code
I keep getting ClientConnectorError on one of my bots, after a while
Is it fixed now?
Nah
Its weird
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
that error means your is_authorized check returned False.

looking at your code, you're overwriting the authorized users variable with an empty list later on
https://leo.might-be.gay/OZNN08.png
I don't know much about coding so yh this just a bot i want to make free to use for alot of people cuzz it was hard to use first
if your config file does have the intended users then yes, deleting the second definition would fix that
lemme try
can i also delete thse part
44 43
consider taking a bit of time to learn the basics of python before diving right into something like discord.py (it is not super beginner friendly)
yh ik know now 

and, does it work now?
i was asking something 
hmmmm https://leo.might-be.gay/KNJ63R.png
- that's not a thing.
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
ah
I shall step out of this conversation now. Adios

if you wanted to know, no it didnt work
It was once, it had been deprecated for about 2/3 years now
@commands.Cog.listener()
async def on_message(self, message):
banned_words = ["shit"]
print(message.content)
for word in banned_words:
if word in message.content.lower():
await message.delete()
await message.channel.send("That is a banned word!")
await self.bot.process_commands()
Any reason for why this isnt printing anything? I have intents enabled for everything as well
on_message_edit and on_message_delete work normally for me, im only having a problem with on_message
show how you're enabling your intents?
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="g!", intents=intents)
nvm i found the issue, there was some other on_message event in my code which was overriding this
@slate swan #python-discussion message Are you using discord.py? What version? Since 2.0, you should do member.avatar.url and not member.avatar_url. Also, instead of whatever you're doing at the top there to default to the author, you can do this:
@client.command()
async def avatar(ctx, member: discord.Member = commands.Author):
...
If someone wanna do a chatbot with custom data dm me for join the project
I had a bit of a funny joke idea. Basically listen to voices for specific movie quotes then play that sound byte from the movie
maybe you're missing intents?
can you show the part of your code where you make the Bot?
so it works for that command but none of the others?
There’s no point enabling all intents if you override it with default intents again
can u show all of your code?
Oh it's your on message
make @client.event into @client.listen()
for on_message
does it not work when you pass in member or only when you pass it in?
I want to write a discord bot that is unique and provides practicality but I am not able to come up with an idea. Any suggestions?
It's better to ask the people themselves what they prefer/would use
most such bots have already been created. the only ones you could do are bots to automate some very specific or niche problem which you have
Actually I was thinking of:
- A forum management bot that manages the forums channels on discord. As well as being able to enable "macros" that adds more functionality to the forum.
For example, a macro that will add "upvotes" and "downvotes" to a post. And some commands within the macro that will display the stats of a post.
- Kind of an experiment tbh, a discord bot that manipulates the server using AI. The user will be able to just ping the bot and type in their request, something like "@bot create a text channel of name 'general', add the default permissions" or "@bot create a new channel 'replica' and replicate 'general' channel".
As I mentioned, I want to try it out as an experiment to see if it's actually more efficient.
- Open Source bot, basically the bot can be hosted by anyone. This bot will have an interactive dashboard that will allow user to add/remove "plugins", these plugins will be features for the bot. Basically anyone can write and publish their plugin.
I would like to know your input on these ideas. And if you have any criticism/feedback please share it.
A friend of mine had an idea, but abandoned the project, so if you find the idea interesting, you can make it
He thought about a modular bot, which has a simple base, and everyone can create plugins. After a verification, these plugins are published, and people can add it on their bot
at first, there are only a few plugins built in, like some classic moderation, tickets or other, and then functionnalities of the bot would improve with time
Yeah that's what I thought about as well
How to make nsfw commands only show up in nsfw channels?
I think there is a way to do that right?
This is all I have found, which is for cogs, I am kinda just trying to do it for commands?
slash commands?
Yes ^
Trying to do it for sub commands, which I can't find anything, or Im looking in the wrong spot
try setting the nsfw argument to True in the decorator
I have done that, it doesn't work
did you resync the commands?
Yes
and restart your client
Yes
that's weird hmm. I'm not quite sure if you can do that then
I mean you can with cogs, but the issue with me doing just the cog is it also has SFW not just only NSFW, meaning the SFW would have to be in a NSFW channel, I am not really trying to seperate the cogs when there should just be a way to have a check on it..
Put it true inside of the command itself, and I also put it true inside of the group
It seems to just not be a thing, unless there is a differen't way of doing it.
but app_commands.Command does have a nsfw argument that is set to False by default
oh you're using hybrid commands
Yes
that doesn't matter it should work
wait for some time after you sync the commands using nsfw set to true
I do a manual sync, so then after I sync I just do ctrl + r which should completely refresh discord, and it should be updated
hmm yeah I know. just wait for like 5 minutes and refresh
it takes some time for discord to act up
Idk, that shouldn't matter imo. But Ill wait lol
can you send the docs on this?
class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.
These are usually not created manually, instead they are created using one of the following decorators:
• [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command)
• [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command)
• [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command)...
ty
Thats weird, it should work then
Glad I read it, it will not work on sub commands, which makes sense now
oh 💀
Well that makes sense why it isn't working 😭
don't use subcomands then
or don't make nsfw commands. become good boi

I don't think it even works, because when I have it on, the nsfw commands show anywhere, and I can run the commands anywhere too. So I think I can just continue with a simple check of if the channel is nsfw.
I just wanted to hide the commands unless you were in a nsfw channel, but I see its not really working.
So its fine, but thanks for the help.
Guys
i'm using discord.py and mysql
Doing queries through bot
After running bot and some hours , when i execute an query , it gimme :
discord.app_commands.errors.CommandInvokeError: Command 'create' raised an exception: OperationalError: 2055: Lost connection to MySQL server at 'serverip:3306', system error: 10053 An established connection was aborted by the software in your host machine
how I can set max bitrate? (problem by boosts)
when using a custom check for a discord app command, is there a direct way to make it not raise an error when returning False?
What is custom command for Discord and where to find it ?
Make some storage free on your pc
You can catch the exception
I'm mobile
Is there a language in the name of custom command especially for coding bots? @red blade
what do you mean like being able to make custom commands for a specific server?
how do you link a slash command in an embed?
</full command name:command id>
how do you get the command id?
CommandTree.fetch_commands and CommandTree.sync both return list[discord.AppCommand], then you access the AppCommand.id
ok thx
how do you make a command, that repeats other commands for a specific amount of given times,
i already have wrote the command and arguments of it, but i don't know what should i write for the functionality of it
is this command meant to be an owner-only command?
yup
then check out the jishaku extension for discord.py, and its jsk repeat command
for _ in range(1, time+1):
command = self.bot.get_command(text)
print(command)
await ctx.reply(F"Repeated `{text}` - `{time}` times")
``` i'm trying to use the get_command method but it only returns None
you are probably getting None because get_command takes only a command name
i am only writing the command without the prefix...?
🤔
and i totally forgot that jishaku existed
hold on wait a minute
ctx.reply
jishaku doesn't work for anything but discord.py
that does not look like discord.py
even jishaku doesn't recognize the command
but it is?... wdym? i am using dpy
oh wait I misread something
I somehow read ctx.respond which is from some other library
my bad
it's ok
i don't know why this doesn't work now
this is not a slash command right?
and dm.waifu works right?
if it does, then that's pretty weird
i figured it, i had 2 different commands have the same "function name"
and now also my command works, it won't return None anymore, but i don't know how to run the command
also figured that out, used await command.__call__(ctx)
ty for reminding me about jsk tho, leonardo
no problem
which is the same as await command(ctx) btw, dunder call is to determine the behaviour of ()
oh didn't know
that is far more complicated, because of the parsing of the arguments. jishaku does context manipulation for that
are boost bot against discord tos
yes
To pass local function variables into nested bot.event() functions like on_reaction_add I created a global "temp" variable that holds data inbetween the nested functions, now I"m wondering if this will be a problem if two people use a command that alters this global variable. What would happen?
Generate a new one
First of all dont use a global variable. Use a bot variable (run !botvar for more information).
And what are you storing in this variable?
im storing the message the bot just sent to check if the next reaction is from that message
Then you should use a list to store the message ids right? You may have multiple commands run for using that feature
So you would of course have multiple ids to store
i really just need a way to pass local variables to the nested bot event functions
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
i have
So anyone here has any idea about ephemerals? Mines not working
Also my cooldown isnt working either.
I am using multiple functions inside my discord function.
i found out that you can mute/unmue the client using the rpc api. wanted to test it out to work on a script for electron wayland users of discor (like me) that dont have native support for keybinds... so how to use it with pypresence?
And any idea how to enable slow mode?
code?
If I try to cache a function that takes ctx as a parameter, will it work?
Every time ctx object will be different. So it won't really work the way I expect it to be, right? Or am I wrong?
You can store and use contexts later, yes
Maybe except for interaction-based ones, not sure
I will upload it on GitHub and then send you the link to repo.
it may not work the way you expect. cache function should only take exactly what it needs and nothing more
if you don't do that you get false negatives with cache hit which is bad
Hmm...

Hey! I'm currently using nextcord, and I want a opionon on smthing. Should i seperate each command into a diff file (Like for discord.js) or group them together (so like ping.py help.py vs utils.py moderation.py)
Of course, you should group the related commands together.
alr thanks, i was messing around with discord.js and it made me think lol
Old XP Count 0
Total Message Xp 0.09999999999999999```
It is always displayed in db 0, even overwrite the new xp
anyone know a good vps to use when developing with other people?
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 659, in connect
await self.ws.poll_event()
File "/usr/local/lib/python3.10/dist-packages/discord/gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
This is due to network right ?
is it just me because im trying to block commands in dm's. i thought it worked before, but now it doesn't. I have:
@commands.guild_only()
@discord.app_commands.guild_only()```
Only recently I have realised that they still try to work in DM's, when it shouldnt
My bot won't ever seem to find the users in the guild, is there any way someone is able to help me?
?tag intents
This is not a Modmail thread.
wrong one 😦
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.
I have them to my knowledge/
did you enable them on the developer portal as well?
yep
can i see your code were you did the intents
import discord
from discord.ext import commands
from discord import Intents
intents = Intents.default()
intents.members = True ```
and then i take it you added intents = intents on the end of the line where you declare the Bot
ok then can i see the part of the command where it isnt working
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@client.command()
async def warn(ctx, member: discord.Member, *, reason=None):
if reason is None:
await ctx.send(f"{ctx.author.mention}, please provide a reason for the warn.")
return
# Send a warning message to the specified user
await ctx.send(f"{member.mention} has been warned for: {reason}")```
this can never seem to find a user
^ sorry for delay
Literally nothing happens
thats weird i just tried it and it worked
Very odd.
Try and put another command, just a test one, just something simple like
@client.command()
async def test(ctx):
await ctx.send("Testing")
And just check if that works
it's got a slight error but idk how to fix it since i see nothing wrong
It's saying priviledged message content is gone
but i'm like 100% certain it's enabled
okay
can somebody have a look at my bot and see where things are going wrong. it's aim is to allow a discord user to connect their twitter account and assign a role respectively:
https://paste.pythondiscord.com/BVWA
what do i need to add
if you want to do all intents, you can use intents = Intents.all()
let me try now
ok
ty ty it works
now my other command is broken 😭
which is?
a warnings command ironically
do you get an error?
it think it's just full of errors lol
can i see it
@bot.command()
async def warnings(ctx, member: discord.Member):
# Check if the user has the necessary permissions to view warnings
if ctx.author.guild_permissions.kick_members:
# Get the user's warnings
user_warnings = warnings.get(member.id, [])
if user_warnings:
await ctx.send(f"{member.mention} has {len(user_warnings)} warnings:\n{', '.join(user_warnings)}")
else:
await ctx.send(f"{member.mention} has no warnings.")
else:
await ctx.send("You don't have the necessary permissions to view warnings.")```
this is the code, i can grab the error if it's needed
yes ill take a look at the error
Attribute Error: 'Command' has no attribute get
oh yes, is warnings a dictionary?
not at present
i would probs need help to set that up
then what is warnings.get()
a thing made with the assistance of AI
right, well 1, warnings is the same name as the command, so it will think you are trying to run .get on a command which you can't do, and 2. it will need to be a dictionary or something to use .get
so the dictionary would need a different name, however that would not be advisable to use
a database would be more suitable
can you help me to set either of those up?
i've changed it to warningslog.get
how would i make a database?
databases can be difficult if you haven't used one before, for small bots, SQLITE is ok and for larger bots, ones like POSTGRESQL are better. For a small bot, you can try and find a youtube video for it. However, i would recommend using aiosqlite and not just sqlite. This is because it is AsyncIO so other coroutines can run simultaneously
cgs on confusing me 100 times over in a single message, i'll look into it, thanks for the help
😭 and no problem
if anyone could take a quick look, would be really helpful
i am having problems with the twitter callback i believe
So I've just stumbled upon this in the docs: https://discordpy.readthedocs.io/en/stable/api.html#discord.ClientUser.locale
My understanding of this is that the API tells the bot what language the end-user is using.
Also, am I able to nest groups like this?
parentgroup = bot.create_group("parent", "parent group commands.")
childgroup = parentgroup.create_group("child", "child group commands.")
you can nest groups but not like this
the .create_group method has been removed in 2.0 version
Sorry I should have clarified, this second question is using pycord as it's lib
wouldn't work in this case, but i found a work around by using nonlocal i think
just state your question/problem
hi, i'm trying to write a bot that checks messages for a specific regex pattern, and then send a message if it matches - but I can't seem to actually get it to match to anything? even sending message that should match (and match when testing in other things), any help would be appreciated <3
@client.event
async def on_message(message):
match = re.match(r"/\d+,\d+/gm", message.content)
print(f"{match}")
print(f"{message.content}")
if match is not None:
await message.channel.send("stop using decimal comma!!")
edit: screenshot is terminal output of it sending stuff after me sending messages
how to make the bot ping someone
Are you trying to match stuff like 1,1? If so, that pattern won't match
!e it'd match things like these
import re
pattern = r"/\d+,\d+/gm"
print(re.match(pattern, r"/1,1/gm"))
print(re.match(pattern, r"/12,14/gm"))
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <re.Match object; span=(0, 7), match='/1,1/gm'>
002 | <re.Match object; span=(0, 9), match='/12,14/gm'>
oh crap yeah, my bad lmao I forgot that it doesn't use flags or open/close things in the pattern - thank you!
🐈
🐱
Hey, I am making a status page for my bot, and it seems to never load on my server, it loads on local host but never on my website host, can someone help me with the issue?
It works fine on local host but then fails when I upload it to the actual website host, the website works, its just the status page, it takes ages to load, and I am confused on why. Yes I understand this is for python only, but the website is in JS, so hopefully that isn't an issue!
Anybody know why I'm getting an indentation error on "**@**bot.event"?
disnake latest & py
@bot.event
async def on_modal_submit(modal_inter):
url = modal_inter.text_values["banner_url"]
code = modal_inter.text_values["code"]
channel = modal_inter.text_values["channel"]
admin_role = modal_inter.text_values["admin_role"]
loa_role = modal_inter.text_values["loa_role"]
with open(file) as f:
data = json.load(f)
if str(modal_inter.guild_id) not in data:
data[str(modal_inter.guild_id)] = {}
data[str(modal_inter.guild_id)]["banner_url"] = url
data[str(modal_inter.guild_id)]["code"] = code
data[str(modal_inter.guild_id)]["channel"] = channel
data[str(modal_inter.guild_id)]["admin_role"] = admin_role
data[str(modal_inter.guild_id)]["loa_role"] = loa_role
with open(file, "w") as f:
json.dump(data, f)
await modal_inter.response.send_message("Setup complete!")
@bot.slash_command()
async def setup(inter):
# Create and send button
@bot.event
async def on_button_click(inter):
components = [
TextInput(label="Banner URL", custom_id="banner_url"),
TextInput(label="Game Code", custom_id="code"),
TextInput(label="Guidelines Channel", custom_id="channel"),
TextInput(label="Admin Role", custom_id="admin_role"),
TextInput(label="LOA Role", custom_id="loa_role")
]
modal = Modal(title="Setup", components=components)
await inter.response.send_modal(modal)```
!traceback and full code, please?
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Resolved, caused by unfinished slash command directly above bot.event. Thanks though!
Hey guys
Anything able to help me to figure out why this bot is coming up with an error? It's seemingly unable to find such thing as a role.
post error
sorry it's an image copying it is a nightmare
can you post the full thing
the code or more of the stuff below?
the more stuff below
the full error
and if what you blacked out is anything other then the actual name of the file on your computer send that to pls
it's just the file name
You passed the discord.role module (discord/role.py) and not the discord.Role class from it. Uppercase that R
coding just has to be so picky ty tho
now i have another isse 😭
@bot.command()
async def modbind(ctx, role: discord.Role):
if role is discord.Role:
await ctx.send("Binded successfully to {role.mention}")
else:
await ctx.send("Improper role.")```
this always seems to come up with Improper Role.
A role class will never be equals to a role instance. Let alone be the same in memory
- The check you would use is called isinstance,
if isinstance(role, discord.Role) - that check is useless, because it will always be that class. When it fails to convert it will raise an error, and not execute the command's body. If you want to send that message when an improper role has been passed, you need to create an error handler
Is there a way for me to reference that role in another command?
As in?
As in mentioning the role in another command, to ping it.
You'd have to store it somewhere, but yeah
Say a variable, like a dict of server -> role
Or if you need permanence across restarts, then a database.
I theorectically would need it to remember but for the purpose of testing there is no need.
@bot.command()
async def modbind(ctx, role: discord.Role):
await ctx.send(f"Binded successfully to {role.mention}")
mod = role.mention
@bot.command()
async def mod(ctx):
await ctx.send(f"{mod.mention}")```
and it doesn't mention, is there any way i can do this?
You might want to learn about function scopes (!scope) and bot variables (!botvar)
how do we make like this?
Buttons?
nono
What is it, then?
you create an embed in the callback (button) and send it along with more buttons
@ui.button()
async def button(...):
embed = discord.Embed()
await interaction.response.send_message(embed=embed, view=View())
Something like this would suffice
OHHH
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
This is a channel to help people develop discord bots. You should use #bot-commands to use the bots
How do other bots have space in the command name? When I tried it it gave me a big silly error
Those are called groups
and how do i create such groups?
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
An example:
from discord import app_commands
class MyGroup(app_commands.Group, name="something"):
@app_commands.command(name="subcommand")
async def callback(...):
...
(maybe? I just typed that live)
and that would then lets say be shown as /ticket something ?
Yes
okay thank you
Old XP Count 0
Total Message Xp 0.09999999999999999```
It is displayed but the DB always says 0 😱 I round it off with `round(new_xp_count, 2)`
Bump
how often does this error happen?
ehhhhhh safe to ignore probably
this means that hey, you unexpectedly disconnected from the websocket
could be network issues, blocking code, [random discord outage - unlikely], other stuff?
Ye so prolly due to unstable vps network ?
¯_(ツ)_/¯

most likely blocking code or unstable network
from experience 😩
holy shit it's umbleh 
i look at this chat occasionally 🙄
yea same
though 99% of the time someone already got their questions answered
and the other 1% is one of those questions that make me roll my eyes so backwards I can see my brain hiding away
but I try to be helpful anyway, because thats the point
fr
hello, ive been running this script for a while, probably close to 3 years. minor bugs, bug usually i can quick fix it. but with that one im not sure how. can anyone point me in the direction for a fix? traceback shared in this pastebin
is this the entire traceback
yes
it looks like this might be of some use
https://github.com/Rapptz/discord.py/discussions/9561
thanks im glad it isnt caused by something i might have done lol. so i guess ive gotta wait for 2.4
edit? was a fix posted, i dont seem to find it
i mean changing the lines in gateway.py from
elif msg.type is aiohttp.WSMsgType.ERROR:
_log.debug('Received %s', msg)
raise msg.data
to this instead
elif msg.type is aiohttp.WSMsgType.ERROR:
_log.debug('Received error %s', msg)
raise WebSocketClosure
alright, ill try it out thanks
Hello i have how could I create application commands (slash command)? With the discord.py library
The documentation for the CommandTree will be of use to you as it's your primary interface for working with slash commands
!p discord.py
Converting to "int" failed for parameter "pep_number".
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
then after you create them, CommandTree.sync to register to discord
https://about.abstractumbra.dev/discord.py/2023/01/30/app-command-basics.html#syncing
To cut all the yapping, basically
@bot.tree.command()
async def my_command(interaction: discord.Interaction):
await interaction.response.send_message("Hello from my command!")
Then register
await bot.tree.sync() # global
# OR
guild_id = 267624335836053506
await bot.tree.sync(guild=discord.Object(guild_id)) # guild specific
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "/home/modmail/auxiliarius/cogs/events.py", line 230, in on_member_join
await file.save(embed.to_dict(), welcome-output)
AttributeError: '_io.BytesIO' object has no attribute 'save'
Hi I'm getting this error with this code and I'm not sure what I'm doing wrong, I don't usually use files with bots or python in general so my understanding of the io module isn't great
embed = discord.Embed(...)
await member.send(embed=embed)
file = io.BytesIO()
await file.save(embed.to_dict(), welcome-output)
admin_commands = await self.bot.fetch_channel(710336551967522887)
await admin_commands.send(file=file)
firstly why are you saving embed as a file and sending as a file? is there a reason?
I have someone who wants to edit multiple sections of the embed but they don't have access to the code. Want I want to do is write the embed dict to a json file, which I can then give to them for edits and then either directly load that file or manually transfer the sections.
This isn't the best solution to this situation but it seems the most convenient solution
Edit: please ping on replies because I'm going to be a bit busy and may miss messages
o
well bytesio isnt an async impl, but tbh you dont really need async impl, you can do the followingg with stringIO, its just the same as bytesio ```py
stringio = io.StringIO()
json.dump(embed.to_dict(), stringio)
stringio.seek(0)
await channel.send(file=discord.File(stringio, filename='abc.json'))
since embed.to_dict is json serializable, you can use json.dump w/ stringIO since json.dump give str to .write, also the stringio.seek(0) is important, so it reset the cursor for discord.File to read
Sorry for the ping if there was one, your followup answered my question
oke
class Shop(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command(
name="shop",
description="Check your shop"
)
async def shop(self, interaction: discord.Interaction, user: str, password: str) -> None:
val = Valorant(user, password)
embeds = list()
for skin in val.get_daily_skins():
embed = discord.Embed(description=f"Price {skin.price}")
embed.set_author(name=skin.name)
embed.set_image(url=skin.image)
embeds.append(embed)
await interaction.response.send_message(embeds=embeds)
Any reason this is raising interaction not found?
does it take more than 3 secs to respond? might wanna defer it
also make sure get_daily_skins() and valorant stuff isn't blocking
I think it was that
that means it did what it was tasked with and dipped, basically.
or that's what it thinks.
https://paste.nextcord.dev/?id=1710514756205826
He does not disconnect the client
consider using the after= parameter in VoiceClient.play()
see this FAQ
2024-03-15 21:54:37 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-03-15 21:54:37 INFO discord.client logging in using static token
2024-03-15 21:54:39 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 77b93e2be17055c83b454973b8618554).
Krack#8887 has connected to Discord!
C:\Users\Risinplays\Projects\Krack\commands\example.py:13: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(Example(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Example cog successfully loaded.
Failed to load extension example: Extension 'commands.example' raised an error: TypeError: object NoneType can't be used in 'await' expression
Failed to load extension __init__: Extension 'commands.__init__' has no 'setup' function.```
from discord.ext import commands
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Initialize Discord intents
intents = discord.Intents.default()
intents.messages = True # Enable message related events
intents.guilds = True # Enable guild related events
# Create bot instance with command prefix and intents
bot = commands.Bot(command_prefix='!', intents=intents)
# Event handler for bot ready event
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
# Remove the file extension
cog_name = filename[:-3]
try:
# Load the extension and print the return value
extension = await bot.load_extension(f'commands.{cog_name}')
print(f'Loaded extension: {cog_name}, return value: {extension}')
except Exception as e:
print(f'Failed to load extension {cog_name}: {e}')
# Run the bot with token from environment variable
bot.run(os.getenv('DISCORD_BOT_TOKEN'))
why am i getting that error pls explain , ping me pls
show your cog file
class Example(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
async def setup(bot):
await bot.add_cog(Example(bot))```
and also @north kiln i am still getting this error
WARNING discord.ext.commands.bot Privileged message content intent is missing...
even if i have enabled it in the developer portal
intents.message_content = True
!mcintent
your code tries to load the init so don't do that
don't do what
my example extension got loaded
don't load init
how to stop it ?
what?
why send the code again
by mistake
How do I make it so that a field on a command takes all the text after that point into it?
ty chatgpt answered it already but thank you anyway
lol, no problem :)
import discord
from discord.ext import commands
prefix = "!"
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=prefix, intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.command(name='test')
async def ping(ctx):
await ctx.send('TEST!')
bot.run('the token')
why does this not work?
the bot comes online but the command doesnt work
im using 3.12
this is an old feature, as old as using prefixes with bots
so i wouldnt be surprised if it has stopped working
you need to set intents.message_content to True to receive message content.
k
still works i use it rn
i havent seen a bot using prefixes since like 2020
Well a Bot constructor forces a prefix so it's still used.
Time to set banners to your bots
Hello there,
I wanted to ask if it's a good idea to screen all messages for keywords and if it matches the bot sends a custom message. It's a moderately active server I would say so I'm not really sure if it's a good idea. Lmk
Automod does exactly this.
my yaml
commands:
join:
name:
en: "join"
de: "beitreten"
description:
en: "The bot joins your voice channel."
de: "Der Bot tritt Ihrem Sprachkanal bei"```
and the code
```py
with open("commands.yaml", encoding="utf-8") as file:
localizations = yaml.safe_load(file)
@nextcord.slash_command(name="voice")
async def voice(self, inter: Interaction):
pass
@voice.subcommand(name="join", description="The bot joins your voice channel.",
name_localizations=localizations["commands"]["join"]["name"],
description_localizations=localizations["commands"]["join"]["description"])
async def voice_join(self, inter: Interaction):```
Error
File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 497, in _run_event
await coro(*args, **kwargs)
File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 2536, in on_connect
await self.sync_application_commands(
File "C:\VSCode\Python\Lib\site-packages\nextcord\client.py", line 2350, in sync_application_commands
await self._connection.sync_application_commands(
File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 794, in sync_application_commands
await self.discover_application_commands(
File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 870, in discover_application_commands
await self.register_application_command(app_cmd, guild_id)
File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 1038, in register_application_command
raise e
File "C:\VSCode\Python\Lib\site-packages\nextcord\state.py", line 1034, in register_application_command
raw_response = await self.http.upsert_global_command(self.application_id, payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\VSCode\Python\Lib\site-packages\nextcord\http.py", line 399, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name_localizations.en: Value "en" is not a valid enum value.
In options.0.description_localizations.en: Value "en" is not a valid enum value.```
as per the discord api docs en isn't a valid language, it must be qualified as either en-US or en-GB
https://discord.com/developers/docs/reference#locales
https://docs.nextcord.dev/en/stable/api.html#nextcord.Locale
okay so the rest is right?
maybe, i dont use nextcord so i wouldnt know of a better approach
hmm even their example shows the same name/description_localizations
https://github.com/nextcord/nextcord/blob/master/examples/application_commands/localization.py
guess thats how you have to do it
Only the prefixed command works, and the slash one doesn't even sync
@commands.hybrid_command()
async def test(self, ctx: commands.Context):
await ctx.send('test')```
how are you syncing your tree?
did the output of sync return an empty list?
I can do this when making embeds right?
embed=discord.Embed()
embed.title="..."
embed.description="..."
Or something like this
embed=discord.Embed()
...
embed.from_dict(data)
discord.Embed has a title and a description argument in its constructor. You don't have to add those fields post-init. Embed.from_dict is a classmethod, so you don't need an instance to use it
I was syncing my commands only to one server, I removed that and for some reason it started working 😭 😭
but thanksss 🫶
but can I have a instance? I'm declaring the data in a loop like this so I was wondering if I could populate the embed from inside the loop as well
data = ""
with open(project_dir / 'welcome-embed.json') as file:
data = json.load(file)
welcome = discord.Embed.from_dict(data)
Sure. from_embed returns an instance of Embed
You don't need to declare data above the context manager btw
okay thanks for clarifying that for me
Would someone code a discord bot for me? I would make it worth your time.
You were already linked rule nine and given alternative options.
okay so what did i did wrong here in rpu_database?
https://github.com/HirukaRogue/RP-Utilities
like, i'm new to sqlite so i changed my database but it's not working as intended and i get not tracebacks
hey
was anyone successful in creating discordpy bot with django server? I'm planning on creating one and would appreaciate tips from more experienced people.
my plan is to run them in docker containers side by side and comunicate via the django api
**Hi everyone! **
Can anyone tell me how to create multi-sessions so that you can run 10 or more applications.. [python]
And so that you can control them, for example, turn them off and on separately.
that sounds like a job for a process manager not just python, i usually just use systemd
could've just use a websocket to communicate between django and your discord bot, depends on what you really want
class Topgg(commands.Cog):
"""For on_message"""
def __init__(self, bot: commands.Bot):
self.bot = bot
self.allowed_server_id = 1156172652629737532
self.allowed_channel_id = 1156190630603661313
self.allowed_user_id = 302050872383242240
@commands.Cog.listener()
async def on_ready(self):
pass
async def cog_load(self):
print(f'{self.__class__.__name__} has been loaded.')
@commands.Cog.listener()
async def on_message(self, message):
if not message.guild:
return
if (
message.guild.id == self.allowed_server_id
and message.channel.id == self.allowed_channel_id
and message.author.id == self.allowed_user_id
and message.embeds
):
for embed in message.embeds:
if embed.description.startswith("Bump done! :thumbsup:"):
response_embed = discord.Embed(
title="Bump Detected!",
description=(
"Thanks for the bump!\n"
"If you don't mind, please upvote UniBot on Top.gg!\n\n"
"*If you don't mind, please leave a review too!*"
),
timestamp=discord.utils.utcnow(),
color=config.main_color,
)
view = discord.ui.View()
button = discord.ui.Button(label="Upvote UniBot", style=discord.ButtonStyle.link, url='https://top.gg/bot/1156134562418663585')
view.add_item(button)
response_embed.set_thumbnail(url=self.bot.user.avatar.url)
response_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await message.channel.send(embed=response_embed, view=view)
break```
So I have this cog for bumps inside of my server, I am wondering if its possible to get who ran the command from another bot? Like who ran the bump command from disboard.
Use channel.history to get the message that called the bump command
Or just have a check to detect one
Disboard stopped doing prefix, so that means you gotta do something for slash. I mean discord shows who ran the command, but I wish they would let bots access that some how maybe?
If you find anything, please ping me!
!d discord.Message.interaction - here
The interaction that this message is a response to.
New in version 2.0.
!d discord.MessageInteraction.user
The user or member that invoked the interaction.
oh thank you. This should work for if the slash is ran by another bot?
Also, yes it works. Just wanted to let you know!
Thank you for getting me the information!
🐈
I have to use message link or is there a way to use message id
import discord
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
class Restart(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.is_owner()
async def restart(self, ctx):
await ctx.send("Restarting...")
await self.bot.logout()
await asyncio.sleep(5)
await self.bot.start(token=os.getenv('DISCORD_BOT_TOKEN'))
async def setup(bot):
await bot.add_cog(Restart(bot)) ```
2024-03-16 11:27:51 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: f6517a7f486781470d573ef0121093c4).
Krack#8887 has connected to Discord!
Loaded extension: example, return value: None
Loaded extension: restart, return value: None
2024-03-16 11:28:53 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "restart" is not found
2024-03-16 11:29:02 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "Restart" is not found
why its not recognising the command?\
its better to just use context menu instead of as an argument for messages
Sorry but what is context menu?
the command needs to be inside of your Cog class
oh thanks fixeed it
How to make app commands? Or whatever they are called.
And is it true, they can't be in cogs?
yea, because danny didnt bother to implement it, since you can only have 5 context menus, and implementing them in a cog is overcomplicated
Alr, so how to do them?
if you do it in a cog you have to manually add the context menu inside the init
https://github.com/Rapptz/discord.py/issues/7823#issuecomment-1086830458
see the example impl he gave
Okay, but how to make the context menu?
With context menus
do you have to sync them?
:yes:
alr
Can you use modals inside of context menus?
Use the interaction to send the modal 🫠
how can i get a sum number of total slash commands? I've tried everything but it either returns set() or 0...
I tried:
len(bot.get_all_application_commands),
len(bot.commands),
len(bot.all_commands) and everything returns the same
When I react with this emoji it says no reaction please help
@bot.event
async def on_raw_reaction_add(payload):
if payload.emoji == "👍":
print("reaction added")
print(payload.message_id)
else:
print("no reaction ")
What library?
nextcord
I don't know about that
well its basically almost the same as discord.py
No, not at all
You are comparing an emoji object to a string, so it won't be true
You need to convert the emoji into a string with str(), then compare
Is anyone able to help me to do / commands? I'm quite confused.
What's the question/problem? Just ask right away
literally how do i even start to set it up i have no clue
In what library?
^
if str(payload.emoji) == "👍"
This worked thank you
This looks like a nice guide
A hands-on guide to Discord.py
okay thanks
hey! it's told me to put
bot = commands.Bot(...)
but idk what to put in the ... and it's coming up with errors regarding it
... is used as a placeholder for the actual arguments
commands.Bot's required arguments are: intents, command_prefix
Okay
is there a specific value i should put command_prefix as to use / commands?
That isn't how that works.
Prefix-based commands and slash commands are two different things
mhmm
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
set whatever prefix you want for your message commands. It won't change anything in regard to slash commands
Okay
@bot.tree.command(name="echo", description="Echoes a message.")
@app_commands.describe(message="The message to echo.")
async def echo(interaction: discord.Interaction, message: str) -> None:
await interaction.response.send_message(message)```
ive taken this code snippet from the first guide, to give myself an example, and it doesn't show up, how can i resolvve this?
To use the slash commands registered in the
CommandTree, you also need to sync them with Discord. This is done by callingCommandTree.sync(). When you sync your commands, the metadata for the commands is sent to Discord and Discord will create the commands for you which you can access from the Discord client.
...
When you call CommandTree.sync, you sync one scope of the CommandTree, either the list of global commands (sync()) or the list for one guild (sync(guild=discord.Object(...)))`
You can read more about how to sync commands in the Syncing Commands section.
A hands-on guide to Discord.py
Please read the guide thoroughly
ty
After syncing, via the command provided in the guide, it said 1 commands synced globally, then the command proceeded to not show up within the discord server, but did work in DMs.
Did you invite the bot with the application command scope?
I don't even know how i invited the bot now
no longer needed actually
bots get that scope by default, and you cannot disable it (and it got added retroactively to all guilds)
oh okay, do you have any clue why it might be that it's not showing up then?
Okay!
thanks!
:)
(also, this is one of the reasons you shouldn't automatically sync your commandtree, since discord is fucky)
(the other is rate limits- sync in a prefix command instead)
(discord is very funky, i've done a _ command for it since it seems better anyway)
yup! 
Learnt something new
hey so I used the guide, and followed what it said about deleting a message, but it just didnt work. the thing which was supposed to delete the message simply didnt exist
sorry, which guide, and which section? In neither I can find the word "delete"
and more importantly, show your code (and errors)
#discord-bots message this guide. In Deleting Responses section
and what about your code and error?
that section seems mostly correct*
it simply says that it doesn't have that function in existence
lol
this is unfortunately one of the disadvantages about guides that aren't reviewed by many people. Errors sometimes slip through the cracks
by the looks of things its @shrewd apex's guide, so ^^^
(also if people are interested like in writing discord.py guides n stuff, see this)
Is there a way to just make it delete any 1 message before it?
like the message right above the slash command invocation?
!d discord.TextChannel.purge with a limit of 1
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
w/ that it still says that it's not a thing
or now it just does nothing
it's saying attribute error
for it and won't work
im trying to make the bot send a message whenever its active but i keep getting this error, can someone explain why is this happening and how can i fix it?
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
channel = client.get_channel('1138787209735045191')
@client.event
async def on_ready():
print(f'{client.user} | {client.user.id} has connected to Discord!')
await channel.send('The bot is online')
client.run('token')```
error:
2024-03-16 14:05:45 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Yido\Desktop\yidoBot\bot.py", line 14, in on_ready
await channel.send('The bot is online')
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'```
try using ctx.send
might work based on my minimal knowledge
There is no context object there
You will always get None from client.get_channel before the bot is ready, because it relies on cache
Also, it gets an int (integer) object, not str (string)
so what can i do about it, what should i change in the code to fix this
so should i put it after the @client.event async def on_ready():
tias
I need help with a logs tracker
using webhook
async def on_member_join(member):
if member.bot:
return
specified_invite_link = 'your-invite-link-here'
if member.invite and member.invite.url == specified_invite_link:
server = member.guild
# Create an embed to send in the logs channel
embed = discord.Embed(title="Server Joined!", color=0x00ff00)
embed.add_field(name="Server Name", value=server.name, inline=False)
embed.add_field(name="Server ID", value=server.id, inline=False)
embed.add_field(name="Owner", value=server.owner.name, inline=False)
embed.add_field(name="Member Count", value=server.member_count, inline=False)
embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)
# Get the logs channel and send the embed
webhook_url = 'your-webhook-url-here'
webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
await webhook.send(embed=embed)```
help
whats the issue?
do u have members intent enabled?
alsu u sure ur invite link is correct?
do u get any errors?
intents.members = True
Yep
no
add a bunch of debug print statements inside the function and the if condition to see if everything is working as expected
I did that but It didn't send anything in the terminal
!paste can u paste all of ur code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
send full code then
its likely the event is not even being triggered
here
Not sure what you're trying to check and compare, but discord.Member.invite doesn't exist
import os
import discord
import asyncio
from discord.ext import commands
intents = discord.Intents.all()
client = commands.Bot(command_prefix='-', intents=intents)
intents.members = True
@client.event
async def on_member_join(member):
print(f"Member {member.name} joined the server.")
if member.bot:
print(f"{member.name} is a bot, ignoring.")
return
specified_invite_link = 'https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands'
if member.invite and member.invite.url == specified_invite_link:
server = member.guild
print(f"Member {member.name} joined using the specified invite link.")
# Create an embed to send in the logs channel
embed = discord.Embed(title="Server Joined!", color=0x00ff00)
embed.add_field(name="Server Name", value=server.name, inline=False)
embed.add_field(name="Server ID", value=server.id, inline=False)
embed.add_field(name="Owner", value=server.owner.name, inline=False)
embed.add_field(name="Member Count", value=server.member_count, inline=False)
embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)
# Get the logs channel and send the embed
webhook_url = '
webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
await webhook.send(embed=embed)
print(f"Sent embed to logs channel: {embed}")
else:
print(f"Member {member.name} did not join using the specified invite link.")
client.run(os.getenv('TOKEN'))
print(f"Member {member.name} joined the server.") does this print
No nothing prints in the console only Bot is online
try @client.listen() instead
Is there any way to find out whether the discord.Member / discord.User object is a deleted user or not
Stil doesnt work
i know you can check if the user is marked as spammer using this
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
!d discord.PublicUserFlags.spammer
Returns True if the user is flagged as a spammer by Discord.
New in version 2.0.
you can try reading descriptions of other ones and see if it matches what you need
@client.listen()
async def on_member_join(member):
print(f"Member {member.name} joined the server.")
if member.bot:
print(f"{member.name} is a bot, ignoring.")
return
specified_invite_link = 'https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands'
if member.invite and member.invite.url == specified_invite_link:
server = member.guild
print(f"Member {member.name} joined using the specified invite link.")
# Create an embed to send in the logs channel
embed = discord.Embed(title="Server Joined!", color=0x00ff00)
embed.add_field(name="Server Name", value=server.name, inline=False)
embed.add_field(name="Server ID", value=server.id, inline=False)
embed.add_field(name="Owner", value=server.owner.name, inline=False)
embed.add_field(name="Member Count", value=server.member_count, inline=False)
embed.add_field(name="Channel Count", value=len(server.channels), inline=False)
embed.add_field(name="Bot Count", value=len(list(filter(lambda m: m.bot, server.members))), inline=False)
# Get the logs channel and send the embed
webhook_url = ''
webhook = discord.Webhook.from_url(webhook_url, adapter=discord.RequestsWebhookAdapter())
await webhook.send(embed=embed)
print(f"Sent embed to logs channel: {embed}")
else:
print(f"Member {member.name} did not join using the specified invite link.")
!code
also like Krypton said there is no thing like member.invite
Oh but is there any way I can track server using invite link
is any member even joining the server lol cause the first print should still work
what you mean by that
https://discord.com/oauth2/authorize?client_id=1216825929054158858&permissions=8&scope=bot+applications.commands also isnt this bot link?
It is
By any chance is the discord.PublicUserFlags.value set to 0 or some fixed value when the user deletes their account? Can't find anything related to it there
i dont know you have to check by yourself if you have access to account that is deleted i guess
Alr thanks
please help i am using winserver 2022
A guide on fixing verification of an SSL certificate.
hi im making a bot, if anyone would like to join and help work on it then please let me know
guys why arent my commands appearing when restarting the bot, i use pycord
stil not working...
whattt why is it like that
when i play music like 15-20seconde i have this error
[tls @ 0000012cd8020000] Unable to read from socket
[mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd8063380] Packet corrupt (stream = 0, dts = 1290240).
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd804b940] corrupt input packet in stream 0
[mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd8063380] stream 0, offset 0x2c044: partial file
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 0000012cd804b940] Error during demuxing: Error number -10054 occurred
[aac @ 0000012cd8085640] decode_band_types: Input buffer exhausted before END element found
[aist#0:0/aac @ 0000012cd807e200] [dec:aac @ 0000012cd80ccb40] Error submitting packet to decoder: Invalid data found when processing input
[tls @ 0000012cd8020000] Failed to send close message
[2024-03-16 15:27:48] [INFO ] discord.player: ffmpeg process 20892 successfully terminated with return code of 0.
Hi so I'm getting this error when I'm trying to setup some command groups and subgroups using pycord and I'm not finding the error to be very informative of the issue, it also seems to be repeating the same error at least 3 times as part "during the handling of this error..."
management-bot | Ignoring exception in on_interaction
management-bot | Traceback (most recent call last):
management-bot | File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
management-bot | ret = await coro(arg)
management-bot | File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 1312, in _invoke
management-bot | await command.invoke(ctx)
management-bot | File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 372, in invoke
management-bot | await self.prepare(ctx)
management-bot | File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 292, in prepare
management-bot | if not await self.can_run(ctx):
management-bot | File "/usr/local/lib/python3.10/site-packages/discord/commands/core.py", line 390, in can_run
management-bot | local_check = cog._get_overridden_method(cog.cog_check)
management-bot | AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
parentgroup = bot.create_group("parent", "parent group commands.")
childgroup = parentgroup.create_subgroup("child", "child group commands.")
@parentgroup.command()
async def parenttest(ctx: discord.ApplicationContext):
await ctx.respond("Testng if child group commands work at the parent level")
@childgroup.command()
async def childtest(ctx: discord.ApplicationContext):
await ctx.respond("Testng if child group commands work at the child level")

