#discord-bots
1 messages · Page 224 of 1
It needs a type hint tho
not necessarily
it will just parse as string right?
Nope
it raises an error?
You should type hint it
Yes
yo why disnake
Lol
!d discordpy.discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
man what the fuck is this
!pypi discord.py
Hey @uneven hearth!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Can someone please help me?
https://paste.pythondiscord.com/duwanigiki
and choose the type e.g. channel, or from a selection
After the name of the argument do : type
what's for channel type
For example channel: discord.TextChannel
ah ok thanks
It depends on channel
does anyone know what this is and how can i fix this?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SpotifyException: http status: 400, code:-1 - Unsupported URL / URI., reason: None
voice channel
discord.VoiceChannel
thanks :)
Tho I don't think voice channels are mentionable
does anyone know what this is and how can i fix this?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SpotifyException: http status: 400, code:-1 - Unsupported URL / URI., reason: None
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
wonder who selected the colors for discord themes poor taste
also embeds buttons and stuff still show up as prelavent to dark or light mode
.
yes
use whichever u feel comfortable with
why do you create Bot instance 2 times and Intents 4 times
so whats current code?
okay so you still create intents 3 times and those which you send to your bot are without message_content
you are just overriding the intents varriable
whats import B 😂
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
you responded to the interaction before
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
ty
what is the max duration for a mute?
timeout?
yeah
it should be like a month
alright
yes 28 days
okay thanks
I am trying to convert an mp4 audio file to an mp3 for a command in my discord bot. How can I do this?
ffmpeg?
I have tried I cant get it to work
ffmpeg -i filename.mp4 filename.mp3
it's just this
and make sure ffmpeg is in the path
and do I import it at the top of my ptohts,?
it's not a module
oh
well Ive said before I use replit a lot
and this is one thingI am on replit for
cool
so is it still possible on replit
how do I install ffmpeg
what distro?
idk
- I have 3 buttons labeled "A" "B" "C"
- When "A" is clicked the label should be changed to "1" (same msg) and the rest should be changed to "2" "3"
- A button should then wait to be clicked again from the same msg id.
- When button; let's say "1" for example is clicked, it should send 'good job'
I'm not sure how to have the button wait to be clicked again and I dont know how to make it so that only the user who activated the command can click it
class tictacAlpha(discord.ui.View):
def __init__(self):
super().__init__()
self.posC = discord.ui.Button(label='C', custom_id='ttt:C')
self.add_item(self.posC)
self.letter = None
self.num = None
mapLetters = {'A': '1', 'B': '2', 'C': '3'}
@discord.ui.button(label='A', style=discord.ButtonStyle.grey)
async def posA(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Choose `A1`, `A2` or `A3`', ephemeral=True)
self.letter = 'A'
self.num = '1'
button.label = '1'
self.posC.label = '3'
self.stop()
@discord.ui.button(label='B', style=discord.ButtonStyle.grey)
async def posB(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Choose `B1`, `B2` or `B3`', ephemeral=True)
self.letter = 'B'
self.num = '2'
button.label = '2'
Func
@commands.command(aliases=['ttt'])
async def tictactoe(self, ctx, opp: discord.Member = None):
embed = discord.Embed(title="Sample Embed")
embed.set_image(url="https://picsum.photos/200/300")
view = tictacAlpha()
await ctx.channel.send(embed=embed, view=view)
# Wait for the View to stop listening for input
await view.wait()
if view.letter is None:
return await ctx.send('Timed out...')
elif view.letter:
print("yup")
# Check for a valid position
for pos in ['A', 'B', 'C']:
if view.letter == pos:
await view.wait()
for num in ['1', '2', '3']:
if view.num == num:
userPos = pos+num
await ctx.send(f'You chose {userPos}')
anyone know how embed requirements work?
so like the embed needs either a title, or description, or footer or something like that
You can create a blank embed without a title or description if that's what you mean
add_field() requires you have a title and a value if you add it but you can set it to an empty string
yeah i'm talking about the discord api requirements
apparently it's just any part of the embed?
e.g. setting the thumbnail alone works
seems abt right, unless you add like a blank add_field() or blank footer anything should work. eg. calling an empty add_field would result in an error but an empty discord.Embed() is fine
The only way I can think of is using an error handler to check for a typeerror
or using isInstance
discord/embeds.py line 275
def __bool__(self) -> bool:```
awesome
i wish i knew that an hour ago
{
"description": "welcome to my server",
"color": 15255379,
"image": {
"url": "https://i.gifer.com/YnEO.gif"
}
}
i know this is not related to discord.py but why does this webhook message fail
this is empty apparently?
weren't you a helper a second ago? or was that april fools?
that was april fools
ah, my condolences
solved by switching to discord.py's Webhook class 😔
still don't understand what was wrong
whole error ``` File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 204, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
how fix this?
you're not responding to the interaction fast enough
await message8.edit("Deleteing Files...") sleep(0.5)i think bec i have sleep lol
sleep is blocking too
defer, asyncio.sleep, not even sure what you want to do in the first place 🤷
:0 asyncio.sleep
bruh
guys what> AttributeError: 'int' object has no attribute 'delete'
button_callback is not button.callback 💀
i got channel id and i try delete it but it gives me errors D: await channel_id2.delete()
button.callback = button_callback
ok!
i'm assigning it though
apparently it's not the same as the button decorator
Hello there!
I need help with my command I dont want any suggestions just please help.
@slash.slash(
name='8ball',
description='Ask the Magic 8-Ball a question',
options=[
{
'name': 'question',
'description': 'The question you want to ask',
'type': 3, # Type 3 represents a string input
'required': True
}
]
)
async def eight_ball(ctx, question: str):
responses = [
'It is certain.',
'It is decidedly so.',
'Without a doubt.',
'Yes - definitely.',
'You may rely on it.',
'As I see it, yes.',
'Most likely.',
'Outlook good.',
'Yes.',
'Signs point to yes.',
'Reply hazy, try again.',
'Ask again later.',
'Better not tell you now.',
'Cannot predict now.',
'Concentrate and ask again.',
'Don\'t count on it.',
'My reply is no.',
'My sources say no.',
'Outlook not so good.',
'Very doubtful.'
]
response = random.choice(responses)
await ctx.send(response)
and what's wrong exactly
also a separate question - how do i use a converter from a modal when i don't have a context 
how much does your converter depend on ctx? ideally you'd extract the needed code to a separate function that doesnt depend on ctx
Are you using a converter on the modal fields?
Maybe you'd be able to create a fake context from the interaction
you could also transform your interaction into a context object, but then you have the weirdness of raising CommandErrors when there isnt actually a command
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
oh nevermind thats not applicable to message components
wait, the code does seem to technically allow it
https://github.com/Rapptz/discord.py/blob/v2.2.2/discord/ext/commands/context.py#L256-L283
i'm using TextChannelConverter and RoleConverter
yeah i'm in a modal
no formatting, autocompletion, or option type validation with modals 😔
you converted the modal contents to ints?
the source code seems easy enough to copy yourself or fake the context object for
https://github.com/Rapptz/discord.py/blob/v2.2.2/discord/ext/commands/converter.py#L506-L507
https://github.com/Rapptz/discord.py/blob/v2.2.2/discord/ext/commands/converter.py#L662-L675
can i get a bot instance from an interaction
oh wait interaction.guild.me
oh interaction.client nvm
@hushed galleon do you know if there's a way to add all buttons using the button decorator at the very end instead of beginning since i am also using add_item
cursed solution
basically just clearing and re-adding them to force them to appear at the end
yeah thats what i would do
now there's just one more issue of pings not pinging anyone despite allowed_mentions allowing it
looks like this is a bot-wide issue
even though i removed allowedmentions completely
doesnt jsk apply its own allowed mentions?
does it work if you manually send a message
uh
oh that does work
now why wouldn't it work for the command
oh now it does work
magic
OH I'M STUPID BOT DOES NOT HAVE PERMISSIONS
can someone possibly help in #1093051478178009229 please
Hello, I would like to add the permission for which the roles I authorize have the power to execute this command, how should I do?
With a Bot command()
how to host my bot 24/7 free?
on the internet @pine plover
!d discord.ext.commands.has_roles
No documentation found for the requested symbol.
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@vale wing item = rôles ?
exemple : @commands.has_permissions(⚔️ General🍻 )
is that it? and if I have more than one role?
Is this a good implementation of it?
@app_commands.command(name='test', description="test input")
@commands.has_role('Test')
async def test_command(self, int: discord.Interaction) -> None:
await int.response.send_message('Hello!', ephemeral=True)
@test_command.error
async def gpt_handler_error(self, ctx, error):
if isinstance(error, commands.MissingRole):
embed = discord.Embed(title="Error", description="You don't have the necessary permissions to run this command", color=0xFF0000)
await ctx.response.send_message(embed=embed)```
My bot seems to be ignoring the role restrictions :S
~~https://paste.pythondiscord.com/qamizokuhe~~
Issue: not spliting the decimal numbers, causing the message sent '53 years ago' fixed
Nevermind, I was using
@commands.has_role()```
Instead of
```python
@app_commands.checks.has_role()```
Up to how long do slash_commands take to update? For some reason mine stopped updating 2 hours ago, but the unupdated commands still function normally
Read last line
how do I await it lmao
I don't even see where's asyncio.run in your code, you probably provided wrong module
no
async def main():
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await bot.load_extension(f'commands.{filename[:-3]}')
await bot.start("TOKEN")
discord.utils.setup_logging()
asyncio.run(main())```
asyncio.run(main())
Are you running this script specifically
what
u for real want my whole file?
File structure
I mean like this
Ok and your "command" file is one from commands folder right?
yes
Make the main function a normal function instead of an async one
I suspect you have a circular import
Do not import anything from entrypoint script, bring everything that needs to be imported into other module
@unkempt mauve
from main import bot```
import discord
from discord.ext import commands
from discord import app_commands
from main import bot #imported from main
class UptimeCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name='uptime', description='Get bot uptime!')
async def uptime(self, interaction: discord.Interaction):
ready_split = str(bot.ready_time).split('.')
await interaction.response.send_message(ready_split[0])
async def setup(bot):
await bot.add_cog(UptimeCog(bot))```
It's not absolutely a circular import but when you import something from a module you automatically execute it. So by importing anything from main you attempt to run the bot again
then what do I do
The cog file is called with the load_extension in main.py which triggers the setup and passes the bot variable so you don't have to import main no?
oh thank you, its working
I removed the main import and its finally working
Anyone?
Hello, I have a problem with a loop. I need it to check the entire list and if there is 1 match, execute a certain piece of code once. And if after checking all the values, no match is found, then another piece of code should be executed once. But in my case, it executes as many times as there are values in the list. How can I fix this?
Code, but it's a command file, sorry, I cannot share the main file.
https://paste.pythondiscord.com/ososovojan
Sorry for late response, recommended solution is to bring whatever you import to another module and import it from there, another is put whatever code that needs to be executed only on first run into if __name__ == "__main__"
its solved already lol
You should value knowledge anyways
I keep getting the application did not respond error to one of the slash commands I'm trying to make, i tried defer but it didn't help is there a solution for this error?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>')
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run("token")
i actually don't understand
reset your token
and try again
i did
5 times
i tried using a vpn aswell doesn't change anything
which discordpy version do you have
2.2.2
what does -u do
What error
Upgrade mode
ohh
i put in the discord token you copy and paste from the applications page and i updated discord.py, the version is still the same
You sure it's token and not client secret? 🧐
Wait, what's that name
discord pedophile bot
...
wierdest name ever
basically its main point is to ban everyone who is acting weird
ah okay just very wierd file name 💀
ah yeah lmaooo
still didnt do anything
this one
Did you respond to the interaction
Can you show the code
wtf i uninstalled discord.py and i still get this error even tho i dont have the package??
Do you have any other third party discord libraries
Like nextcord, pycord, disnake?
i fixed the issue by uninstalling a pervious python version
however
@bot.command()
async def hello(ctx):
await ctx.send("hi")
why is this a slash command?
i actually dont understand i didnt touch discord.py for 6 months and nothing works like it used to
Show the full code then
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print("worked yay")
@bot.command()
async def hello(ctx):
await ctx.send("hi")
bot.run("token")
Is this really discord.py
@app_commands.command()
async def acceptmarriage(self, interaction:discord.Interaction, member:discord.Member):
if c.execute(f"SELECT * FROM proposals WHERE userid = '{interaction.user.id}' AND memberid = '{member.id}'").fetchone():
x = c.execute(
f"SELECT SUM(count) FROM counter WHERE userid = '{interaction.user.id}' AND memberid = '{member.id}'").fetchone()
z = c.execute(
f"SELECT SUM(count) FROM counter WHERE userid = '{member.id}' AND memberid = '{interaction.user.id}'").fetchone()
number = x[0]
num = z[0]
if number == None:
number = 0
if num == None:
num = 0
tot = number + num
lvl = int(tot / 5)
if lvl < 1:
lvl = 1
c.execute(f"DELETE FROM proposals WHERE userid='{interaction.user.id}' AND memberid = '{member.id}'")
c.execute(f"DELETE FROM proposals WHERE userid='{member.id}' AND memberid = '{interaction.user.id}'")
c.execute(f"INSERT INTO marriage VALUES ('{interaction.user.id}','{member.id}','{tot}','{lvl}')")
c.execute(f"INSERT INTO marriage VALUES ('{member.id}','{interaction.user.id}','{tot}','{lvl}')")
conn.commit()
await interaction.response.send_message("You are now married!")
else:
embed = discord.Embed(title="Please check /proposals to see if they proposed to you!", color=discord.Colour.blue())
await interaction.response.send_message(embed=embed)```
This is what it is like rn
i’ll trying to get the content of a message, e.g when a user says $confirm (name) i want it to get the name, i’ve tried message.content but i get an error
use commands
those are exactly the same
wdym?
I would like to ask something, cause someone texted me to help him with self bot. How much is self bot against discord terms? Also when it is used as a farming bot.
!pypi discord.py
!pypi discord
A mirror package for discord.py. Please install that instead.
You're not responding to the interaction if the if-statements is not true
!d discord.discordpy.ext.commands
No documentation found for the requested symbol.
fucking docs command
huh
ohh that actually makes sense thank u
oh yeah it's not a class
idk
How can I solve this problem
My bot infinitely reflected but performs the action
so like
async def confirm(ctx, name):
await ctx.send(f"your name is {name}")?
read it pls.
i have
there's a text block that it's impossible to miss man
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.command()
async def test(ctx):
pass
# or:
@commands.command()
async def test(ctx):
pass
bot.add_command(test)
What
i dont get why you've sent me the link, i know how to make commands
you've not answered what i want to do
send your code then
Then why didn't you
My bot thinks infinitely with the ban command but it ban the person
i just want to get the message content of a command
Show the code
Just use command arguments
Or you don't know how
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.User, *, reason : str):
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
await interaction.response.defer()
await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
await interaction.guild.ban (member_id, reason = reason)
await interaction.response.send_message(f"{member_id.id} has been banned !")
await interaction.followup.send("")```
Why interaction.response.send_message
Replace it with interaction.followup.send
To correctly respond after deferring
Ok I try
async def confirm(ctx, name):
await ctx.send(f"your name is {name}")
like that?
Yes
My command unban doesn't work
@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction: discord.Interaction, user: discord.User) -> None:
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
await interaction.guild.unban(user)
embed=discord.Embed(title=f"{user} as been unban", inline=False)
embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
await interaction.response.send_message(embed=embed)```
anyone know how to add @unkempt canyon bot from this server to my server?
It's probably a private bot
Elaborate
And what'sinteraction.reply
Its error by me interaction.reply
It only takes the members present on the server as parameters
I want it to take as parameter the user#0000 or the id
Then do it
Set the parameter's type hint ot str
But you would not be able to get the ID of a user from their names and their tags
If the bot doesn't have access to them anyway
But I enter the id if I don't have the name
https://paste.pythondiscord.com/ulojacicax main, https://paste.pythondiscord.com/asayeruhuh config
Bot was doing its job perfectly, coming and palying a sound and kicking it but it comes now and doesnt do anything, just stands like that. What is wrong here?
enecccbflrnlufuvblivdnetctlvdcbggetukcflikvt
you're right ^
some notes:
1.your second on_message event is overwriting your first one (shadowing function names)
2. you should look into discord tasks instead of while True:
3. don't use global variables (like last_message : discord.Message= None )
use bot variables or pass it as an argument in your function instead
other than that, great variable names & documentation 👍
I'm not quite sure if that's even possible on PC, but it's easy on mobile. I think it might be possible tho if you type the multiline text elsewhere and paste it into field, but I never tried myself
Another method is use some symbol for splitting lines and replace it with newlines when parsing to command, or use modal
enecccbflrnlrculdntnbdhhrifgbtllnkubektihjvk
Oh thanks
A modal is more suited for this
thank you but i dont get one thing, bot was working perfectly, was there an update to discord.py to crash that or something?
shift enter maybe
what was ur previous dpy version
its same, i didnt update anything
3 days ago this bot was working perfectly
now its coming channel and doing nothing
nope, if you want i can show you my screen too for debugging
u have an error handler?
i am trying vss debugging, thats it
make an error handler for commands and events
i remember this doing nothing when i was figuring out how to transition my tags to app commands, and apparently it was planned but nothing new has come out
i just did right now
and it doesn't go throught after line 30, final line is 30
it freezes after
voice_client: discord.VoiceClient = await voice_channel.connect()
where did you get a module called Crypto from? is it something you've made? is it some library you installed?
Pretty sure you need to install pycrypto
make sure to install pycryptodome
tried that
hmm. tried it myself, after installing pycryptodome, the missing import message was resolved
what was the exact comman you ran?
clearly you messed something up when doing that, since that does provide the Crypto module
pip install pycryptodome
Can anyone tell me how to online my bot 24/7?
host it on a hosting or your own vps
How can I host
read pinned messages in thread i mentioned
Ah i want in free :((
I thought in free also it's available :;:
Hey looking for some input....
My bot responds to mentions but I am trying to get it to NOT respond to replies.
I have tinkered with a second if statement like this
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
if self.bot.user in message.mentions:
print("SCNewsBot has been mentioned.")
await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")
if message.author == self.bot.user:
return
but that didn't work, I believe because its pulling the replied message not the message its replying to.
I also tried this but this option
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
if self.bot.user in message.mentions and not discord.Message.author():
print("SCNewsBot has been mentioned.")
await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")
but that pulls an issue with calling member
use the MessageType
!d discord.MessageType.reply
The system message denoting that the author is replying to a message.
New in version 2.0.
oh so like if MessageType is reply then don't respond essentially
Yeah exactly
you da best old man
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Hello, is it possible to retrieve parameter values programmatically?
Can you tell us more about what you're trying to do? @meager orchid
Yes, just a moment.
I want to create a slash command that will delete messages in a specified quantity. I have a parameter for the value, but I need to insert its value into the purge command and then output it to users. Honestly, I have recently started working with the library.
Here's the part with the command: https://paste.pythondiscord.com/pekicuqoce
Ah, no. That's not possible
if i use guild_only on a group, will it apply to all of its subcommands
dont think so
how do I get a users username from a users id
fetch_member / get_member
will this work if the bot isn't in a server with them?
I'm trying to make something like discord.id
No
how could I do that
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
if self.bot.user.mentioned_in(message) and not discord.MessageType.reply:
print("SCNewsBot has been mentioned.")
await message.channel.send(f"Hello! I am the NewsBot, say `&formats` for a list of the different news prompts I contain or `&embed` to start creating a news post! If you are having any issues with my functions please tag ian `@blissful badge`.")
am I doing something clearly wrong here @upbeat ice? Trying that reply type out
you would need fetch_user here
you're not comparing the message type to anything
so you're basically doing if mentioned_in_message and false
ohhh
You can just check if self.bot.user in message.mentions, it doesn't count reply iirc
invoke_without_command=True)
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):``` first time working w/ sub commands what should I do next?
the subcommands don't go inside the parent command
fixed that
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
pass
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
# Add role to user here
pass```
but now im confused
#bot-commands
it's @role.command() not @role.group()
not if ur using subcommands lol?
@commands.group() -> @role.group()

!d discord.ext.commands.Group.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
odd, cus thats why it works perfectly for me?
that's because you have like 3-4 levels of nested subcommands
not for all my cmds
only for some, most commands that are subcommands use commands.group and then role.group for instance
cool
only role humans remove and bots remove are subcommands of a subcommand
otherwise, the others are just regular subcmds
!d discord.ext.commands.Group.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
group.group is for creating a nested subcommand
It does not unban when returning user#0000 or id it tells me not found
@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction: discord.Interaction, user: str) -> None:
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
try:
await interaction.guild.unban(user)
embed=discord.Embed(title=f"{user} as been unban", inline=False)
embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
await interaction.response.send_message(embed=embed)
except:
await interaction.response.send_message(f"{user} was not found in the list of banned.")```
unban takes snowflake, not str
If you want to unban member by name you should use a different method cause you aren't able to get ID of the user by their name if bot doesn't share servers with them
How to write snowflake ?
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
Snowflake is basically discord.Object(id) but you don't have ID

And same for /unban member: user#0000
Once again, use this
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jishaku\features\invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
pls fix this
Show your code
okay wait
BotInfo.botinfo() missing required positional argument: 'ctx'
Seems like your custom method
yea i tried that but its not getting fixed let me show my code
Isn't it clear that you just need to parse ctx
class BotInfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bot.command()
async def botinfo(self, ctx):
guilds = len(self.bot.guilds)
members = len(set(self.bot.get_all_members()))
channels = len(set(self.bot.get_all_channels()))
# Memory Usage
process = psutil.Process()
mem_info = process.memory_info()
memory_usage = mem_info.rss / 1024 ** 2
# CPU Usage
cpu_percent = psutil.cpu_percent()
# Disk Usage
disk_info = psutil.disk_usage("/")
disk_total = disk_info.total // (2**30)
disk_used = disk_info.used // (2**30)
disk_free = disk_info.free // (2**30)
message = (
f"**Bot Information**\n"
f"- Name: {self.bot.user.name}\n"
f"- ID: {self.bot.user.id}\n"
f"- Guilds: {guilds}\n"
f"- Members: {members}\n"
f"- Channels: {channels}\n"
f"- Latency: {round(self.bot.latency * 1000)}ms\n"
f"- Developer: Your Name Here\n"
f"- Library: discord.py\n"
f"- Github Repository: https://github.com/YourUsername/YourRepo\n\n"
f"**System Information**\n"
f"- CPU Usage: {cpu_percent}%\n"
f"- Memory Usage: {memory_usage:.2f} MB\n"
f"- Disk Usage: {disk_used} GB / {disk_total} GB ({disk_info.percent}%)\n"
)
embed = discord.Embed(description=message, color=0x00ff00)
await ctx.send(embed=embed)
await BotInfo(ctx)
@shrewd vapor@vale winghere is my command code
await BotInfo(ctx) what
You can't await an object
And what is this even supposed to do
oh sryy my bad
but still getting this error @vale wing
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
What is your setup function in that extension
which extension
Python module where your cogs are
are you doing BotInfo.botinfo(ctx) in ur command??
my all cogs are in single code
whats the full traceback
Your command requests +info lol I think
A bit above
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\jishaku\features\invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\badbo\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: BotInfo.botinfo() missing 1 required positional argument: 'ctx'
its because you need to decorate it as @commands.command() in a cog
await BotInfo(ctx)
what dis is uspoesd to do
you can if the class define an __await__ dunder method 🙂
do you seriously think they did that

i still have it
You don't?
look closely
I'm looking closely and still you don't have it
(looking very close to that cat)
how do i fetch a users display name or global name?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
!d discord.Member.display_name
property display_name```
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
making an afk command
how do i set a display name?
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
do i use member or user in a command?
member i always used in a join message and user in commands but how does that apply?
you need to get member who used command
you use slash or prefixed commands?
using py @app_commands.command() async def afk(self, interaction: discord.Interaction user: discord.User = None) #some code here
!d discord.Interaction.user
The user or member that sent the interaction.
what does that have todo with this?
dont you want to get the user who invoked the command?
then interaction.user returns user who invoked command
then you can just do any methods that apply to discord.Member object
so you can edit his name get his name
anything
Hey guys, my slash commands stopped working like a day ago and haven't updated since.. The not updated versions of the commands are still there and functional but the changes aren't visible in discord. All my cogs are loaded, i tried to reset my discord token but still no changes any ideas?
You either sync globally or didn't sync at all.
could you point me to the right documentation please?
There is no documentation if I can't determine the cause.
I'd have to see how you handle the sync.
This error indicates that the BotInfo.botinfo() function is missing the required ctx argument when it is being called. ctx stands for the Context object which is a parameter passed by the discord.ext.commands framework to commands and event functions.
To fix this error, you need to make sure that the BotInfo.botinfo() function has the ctx parameter defined in its function signature. Here's an example of how you can modify the function definition to include the ctx parameter:
Code:
async def botinfo(self, ctx):
# Your code here```
Make sure that the `ctx` parameter is the first argument of the function, and that the `@commands.command()` decorator is used to define the function as a command.
Once you've made the necessary changes, try running your bot again and see if the error has been resolved.
My bot is rate limit without me knowing why
How would I pass a function as a parameter to choices in Option?
async def faq(self, ctx, question: Option(str, choices=lambda: questionShorts(), required=False)
returns error
TypeError: 'function' object is not iterable
Don't tell me that's replit
You can parse name of the function and get it with dict either using a custom converter or converting the name in command itself
some ptero ig
you get this error cause choices must be list or dict
the function returns a list
So just pass choices=myFunc()
Oh.. I'm stupid thank you a lot!
does it host multiple bots on the same machine ?
Do not speak, when you do not know
You mean you own a hosting service or you use this service?
Is it on cluster or on single machine
Cluster
if multiple bots use the same ip they share the rate limits
You should monitor the traffic of that node
therefore when one gets ratelimited so do all others
I have 3 bots, 2 server FiveM, 3 server Minecraft on the same Ip, just port change
That's single machine...
then what I said is the case here, all 3 have same rate limit bucket so if one of them is rate limited all of them get ratelimited
No I have others for others node
is this with me or @vale wing
Others node is surcharged
Okay then you should just check the traffic and see if it's ratelimited because of excessive amount of requests to discord API
429 is in fact for too many requests to the api
so since they are hosting 3 bots using the same ip, they get rate limited with each other
and to prevent it best thing it to use different ips if possible else somehow use proxies for each one
How can you invoke a command from an event
with bot.invoke(), it wants you to pass in a context object. Should I create one myself? That doesn't seem right, discord.py takes care of that usually
ctx.invoke() would be good, but this would only work if I already have a ctx object. So going from a command to a command, not from an event to a command
Iirc you can somehow get context if you have a message, lemme check docs
commands.Bot has get_context
!d discord.ext.commands.Bot.get_context
await get_context(origin, /, *, cls=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message or interaction.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
Note
In order for the custom context to be used inside an interaction-based context (such as [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand")) then this method must be overridden to return that class...
alrighty and then I can just ctx.invoke()
yes
thanks for that
also
uwu

check if ctx.command is not None
if it is None it means the message is not a valid command
thank you guys
Hey, could someone help me with my discord.py script?
https://paste.pythondiscord.com/aninahoveq
The script is currently only running a simple thing, how can I convert the script, so my bot can do multitasking?
Probably a stupid question but, how do I call a class method from a choices parameter in discord.Option?
class GameRelated(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@classmethod
def get_questions(cls):
...
return questions # List
@commands.slash_command(name="faq")
async def faq(self, ctx, question: Option(str, choices=GameRelated.get_questions(), required=False, description="")):
...
This command prints the error "GameRelated is not defined"
are your questions statically defined? or do you expect them to change often
choices are intended for options that dont change, but if you're planning to update those questions somewhat frequently you should use autocompletion instead
for the latter i dunno how pycord implements it but i assume there's at least a technique similar to dpy
^
Can you tell how
see these resources here
also umbra's guide if ashley isnt enough for you https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
Having a weird issue....
@commands.command(name='commands')
async def send_data(self, ctx):
await ctx.send("__All commands use & prefix__ \nMention me directly to check my status\n**formats** - see the available formats I store\n**embed** - start creating a news post")
channel = self.bot.get_channel(1086293466054656100)
author = ctx.author.name
await channel.send(f"Command list access by {author}")
So I can't tell for sure why this isn't working but it was working before I adjusted the text inside the ctx.send. This is the error, what could have introduced this?
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
ashley 💀
some ppl still dont know 😔
fixed?
Negative
which send is the error? ctx.send or channel.send ?
also, why not create a custom help command?
seems more like what you need
I was told early on to ignore all the help stuff thats built in
And that it was dumb
So I've kinda been doing exactly that.
And theres only like 3 commands so its not a big deal
Plus this issue isn't with it sending the list of commands, its in its reporting function where it says an action was performed in a log channel
USER_ID = '1054495095413555220'
@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:
# Replace with your own message
message = f'{before.name} is now online!'
channel = client.get_channel('976797676714749986') # Replace with the ID of the channel where you want to send the message
await channel.send(message) I wrote this code to give a message when a certain user goes online but it isnt working can someone help me fix?
USER_ID should be an int, not a string
ok so thats the issue?
correct
so channel id should also be int
yeah, I still need full error logs & relevant code...
correct
That is the only relevant code
that's one of the 2 things I asked you
I had to go get the full error....
Sorry that I didn't have it ready
2023-04-06 13:04:06 ERROR discord.ext.commands.bot Ignoring exception in command previews
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\Bots\SCNewsBot\responses.py", line 21, in previews
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
File "d:\Bots\SCNewsBot\responses.py", line 21, in previews
still not working
current code?
it's not a yes - no type question
yeah, you should definitely have member intents enabled
in dev portal as well as in code
but you just said "not working" so I assumed errors, I guess it's not even running the event
that's the downside of being vague
proof?
alr, and in code?
import os
from keeprunning import keep_alive
import random
import discord
from discord import Intents
from discord.ext import commands
TOKEN = os.environ['TOKEN']
intents = Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix=".", intents = intents)
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
USER_ID = 1054495095413555220
@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:
message = f'{before.name} is now online!'
channel = client.get_channel(976797676714749986)
await channel.send(message)
keep_alive()
client.run(TOKEN)
alright, found your issue
you don't have presence intents enabled in code
you have to enable in code too?
so this part
after.status == discord.Status.online
will always be False
yup, it's not default
ok so whats the code to enable
take a guess
you've figured out how to enable members intents, what would it be for presence?
intents.presence?
ok
intents.presences
yup
ok thank you
gl!
still isnt working
code?
this but with presence intents true
proof
also, how are you testing this?
alt account
and you're sure the ID is correct?
import os
from keeprunning import keep_alive
import random
import discord
from discord import Intents
from discord.ext import commands
TOKEN = os.environ['TOKEN']
intents = Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True
client = commands.Bot(command_prefix=".", intents = intents)
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
USER_ID = 1054495095413555220
@client.event
async def on_member_update(before, after):
if before.id == USER_ID and before.status == discord.Status.offline and after.status == discord.Status.online:
message = f'{before.name} is now online!'
channel = client.get_channel(976797676714749986)
await channel.send(message)
yeah i copied it directly
seems fine
maybe you'd want to use this event
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_presence_update
instead
ill try
in this case btw
intents = Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True```
you can just use Intents.all()
yup
ok
print something in the event, to confirm it triggers
ok
can someone help me pls ?
import time
time.sleep(2)
print("Welcome !")
time.sleep(2)
file = open("test.txt", "w")
file.append("Testttt")
Yes you open file in read mode
So you cant write
okay
you are still opening it in read mode?
Do you know how to work with files?
a bit
Do you know how to open a file in write mode?
yeah sure
@client.event
async def on_message(message):
# Define the user whose messages you want to react to
user_id = '503127565611958274'
print(f'Message content: {message.content}')
print(f'Message author ID: {message.author.id}')
if message.author.id == user_id:
# Define the list of emojis to randomly react with
emojis = [":grinning:",":kissing_heart:",":kiss:",":heart_eyes:",":heart:"]
# Choose a random emoji from the list
emoji = random.choice(emojis)
# React to the message with the chosen emoji
await message.add_reaction(emoji)
print(f'Reacted to message with emoji: {emoji}')```
I want my bot to react to all the messages user_id sends
but for some reason it is reading them but not reacting to it
what am i doing wrong ?
@slate swan
file is not a console command
huh ?
You executed it as console command
yow someone help i feel stupid here
im having problems
my code isnt working at all or showing up as a embed and theres no errors
@slate swan
from discord.ext import commands, menus
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Ping.py is loaded!")
@commands.command()
async def ping(self, ctx):
bot_ping = round(self.bot.latency * 1000)
await ctx.send(f"Pong! {bot_ping}ms")
@commands.command()
async def pages(self, ctx):
pages = []
for i in range(50):
page = discord.Embed(title=f"Page {i+1}", description=f"This is page {i+1}.")
pages.append(page)
paginator = menus.MenuPages(source=menus.ListPageSource(pages, per_page=1), clear_reactions_after=True)
await paginator.start(ctx)
async def setup(bot):
await bot.add_cog(Ping(bot))
you never closed the file
That's true, I didn't close the file. Is there anything else I can help you with?
oh yeah my bad
No problem. Is there anything else I can help with?
looks like a bot
it worked noice
thanks @slate swan mababe
now it shows this
did you read it?
that one i read, and i cant find anywhere to enable or disable intents
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
try:
if member is None:
member = ctx.author
icon_url = member.banner.url
bannerembed = discord.Embed(title=f"{member.name}'s banner",
color=0xFFFFFF)
bannerembed.set_image(url=f"{icon_url}")
await ctx.send(embed=bannerembed)
except Exception:
embed=discord.Embed(description=f"failed to load {member}'s banner")
await ctx.send(embed=embed)``` when im doing my banner command the command itself won't load but itll say its failed to load my banner??
you go into Bot section and there is Privileged Gateway Intents header
there are intents
enable those that you use in code
@slate swan the python program won't execute :
print("Welcome !")
file = open("file.txt", "w")
file.write("Testttt")
what wont execute means
what did you try
to launch the program with python
(double clicking on this file)
so it means there are some errors
why dont you use some ide to help you?
like VS Code
i'm using it
so why are you running a file from file explorer
bcz i can't run it from vscode
💀
and why is that?
idk how

did you install Python extension?
sure
then there is in top right start button
yeah i tryied
and?
i didn't get the python option beforce
before*
what is python option
when i try to respond to an interaction, why does python give this bug?
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
When the bill gates is chatgpt ripoff
I recall this being an LSP error others ran into as well
doesn't even look like replit lmao
When I see ratelimit error in this channel I get neuron activation
Although I don't even remember how replit looks like
Why'd you scroll up and reply specifically to that message tho 🧐
type checker bug
is this pycharm ?
im having problems
my code isnt working at all or showing up as a embed and theres no errors
from discord.ext import commands, menus
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Ping.py is loaded!")
@commands.command()
async def ping(self, ctx):
bot_ping = round(self.bot.latency * 1000)
await ctx.send(f"Pong! {bot_ping}ms")
@commands.command()
async def pages(self, ctx):
pages = []
for i in range(50):
page = discord.Embed(title=f"Page {i+1}", description=f"This is page {i+1}.")
pages.append(page)
paginator = menus.MenuPages(source=menus.ListPageSource(pages, per_page=1), clear_reactions_after=True)
await paginator.start(ctx)
async def setup(bot):
await bot.add_cog(Ping(bot))```
can anyone help me thanks
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
try:
if member is None:
member = ctx.author
icon_url = member.banner.url
bannerembed = discord.Embed(title=f"{member.name}'s banner",
color=0xFFFFFF)
bannerembed.set_image(url=f"{icon_url}")
await ctx.send(embed=bannerembed)
except Exception:
embed=discord.Embed(description=f"failed to load {member}'s banner")
await ctx.send(embed=embed)``` is there something wrong with my code? It won't send my banner but the embed will load bc thats what it says when i do the command
Cog loaded correctly?
yes
So you can read the on_ready print?
What does it say?
yes
failed to load rott#0001's banner in the embed
You'd need to fetch the user since it's most likely retrieving from cache.
how would I do that I haven't done that before ? (still getting py down while coding sorry!)
Any error handlers?
no not really
Not really?
not yet im saying
That’s good…
So you’re calling the command but nothing gets sent nor are there errors?
@commands.command(aliases=['bann'])
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
member = await ctx.bot.fetch_user(memebr or ctx.author)
banner_embed = discord.Embed(
title=f"{member.name}'s banner",
color=0xFFFFFF
)
banner_embed.set_image(url=member.banner.url)
await ctx.send(embed=banner_embed)
oh nvm i got it@potent spear
Command raised an exception: NotImplementedError:
this is the error
Full error is needed tho
TY
lemmetest it
still nothing for sum reason?
thats all it printed
Can’t be
Then you’re hosting it on some weird shit OR you have error handlers somewhere
@commands.command(aliases=['bann'])
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
member = await ctx.bot.fetch_user((member or ctx.author).id)
banner_embed = discord.Embed(
title=f"{member.name}'s banner",
color=0xFFFFFF
)
banner_embed.set_image(url=member.banner.url)
await ctx.send(embed=banner_embed)
The error is being swallowed
Let's try this...
Fetch_user takes a user not a member object
will this work?
Been awhile lol
Same thing
A member IS a user obj…
No
WORKED
It's not
I’m listening
mhm, makes sense to fetch a user by passing an id
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
Member inherits from User…
Best to use the docs since it literally states that you need to fetch it.
Recopy I saw a typo lol
i fixed it
memebr lol
How so?
Try using it outside a discord bot first, then integrate
Discord is prob more complicated lol
bc I need a token and all of that but I can't
bc with the recruit_uri that takes a minute
and its apart of the code
link = pinterest.oauth2.authorization_url(app_id, redirect_uri) the app_id loads automatically but I need approved for redirect_uri
I'm just trying to make an auto pfp and banner command for where the bot fetches images of a certain style and drops it into the chat
@commands.command(aliases=['bann'])
@commands.cooldown(1, 60, commands.cooldowns.BucketType.user)
async def banner(self, ctx, member: discord.Member = None):
await ctx.send(embed=(m:=await ctx.bot.fetch_user((member or ctx.author).id),discord.Embed(title=f"{m.name}'s banner",color=0xFFFFFF).set_image(url=m.banner.url))[1])
woops
Oneliner 🫠
It still can't take a Member Object
yeah
Never said that
what's lsp?
pycharm bug
I mean can't argue with that but it doesn't take a User either.
that's what i thought- vsc & python don't seem to complain
it does take a user
language server protocol
you are probably just passing it incorrectly
Nah the dpy typing is just very bad.
agreed, the docs aren’t thát filled with examples too :/
Those don't have strict linting.
Well... not that pycharm is strict.. but it's getting there.
honestly 100% strict linting isn't the best either
idk how else to make an auto pfp or banner command without pinterest api bc thats how most ppl make it
Are you self botting?
wdym?
It is type hinted good enough imo, also vs code and stuff don't complain just pycharm
Do you have the discord rpg code for me?
pycharms type checking system is awful
Are you using a user token to login the Discord API?
Well if the IDE cannot read the typehint it's not a good typehint.
if you are making a discord bot then you are using discord bots api, he means using a normal user account with the api is against tos
vscode etc require to install extensions for linting.
oh no I haven't done that
kinda off topic
Idk exactly what you mean by this then
if its a direct link discord will put it there itself
here ill show u
I think they mean this :
they give the bot a pintrest link and it uploads it in chat
probably someone manually uploaded it and then used the discord url
in that case it would need a way to download it
Honestly if all you wanted to do is embed images i'd just use scraping to get the source url and then have the bot post that url.
I mean that'd work if it can do multiple styles like male, female, and other stuff like that
Pinterest doesn't really have an API capable of this.
You'd need to use aiohttp for the html data then use a package like beautifulsoup4 and get the info. Keep in mind that beautifulsoup is sync so you do want to run that in an async executer preferably.
from bs4 import BeautifulSoup as bs4
root = "https://pfps.gg/pfp/"
query = input("search term: ") # test query
def get_page(url):
r = requests.get(url)
return r.content
def scrape_page(url):
pfps = []
soup = bs4(get_page(url), "html.parser")
scraped_pfps = soup.find_all("div", {"class": ["item-details", "text-center"]})
for pfp in scraped_pfps:
child = pfp.findChildren("a", recursive=False)
if child:
pfps.append(child[0])
return pfp_dict(pfps)
def pfp_dict(l):
pfps = {}
for pfp in l:
pfp = str(pfp)
if pfp.split('href="')[1].split('">')[0].split("/")[-1][0:4].isdigit():
pfps[pfp.split('>')[1].split("</")[0]] = pfp.split('href="')[1].split('">')[0]
return pfps
search = scrape_page(f"{root}{query}")
print(search)``` like this?
ewwie no
You'd need to do more research on it. It's not like you can just make this in a day on the first go.
I recommend using the docs from the packages.
Both of them have decent docs.
then ill js pass on doing that ill work on more mod, info, and stuff like that
i cant spend all day on a command
maybe when I'm close to finishing
Lol
The eval command in this server has been ongoing for multiple years with numerous experienced programmers and it still has some issues.
Coding takes time.
can we go into a forum and could u help me w/ a few commands?
You can tag me.
idm
do you guys think its ok to host a bot on a spare old laptop i have? It overheats so im gonna place a fan by it but im scared to keep it on charge 24/7 because it will drain the battery as it will be used 24/7
I don't suggest you use a whole laptop for that because its bad both laptop and bots performance, usually bots are locally hosted on resbarry pis or desktop old computers
or get somewhere very cheap to host on
there is services where you can host for 1dollar a month I think
I found one for 3euros a month
1 dollar no I haven't seen but for 5-6 a month there are nice vps
yes
something named Pebble
yeah..
Command 'gungame' raised an exception: TypeError: Button.init() got an unexpected keyword argument 'label'
button1=Button(label="Join!", style=discord.ButtonStyle.green)
join_but=View()
join_but.add_item(button1)
anyone has any idea
how are you importing Button
show some code
from discord.ui import Button, View
well why don't you use a decorator with a callback function instead
it's much easier `
ye trying that let me check
@discord.ui.button(label="Join!", style=discord.ButtonStyle.green)
async def create_invoice(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_message("Test")
and then put this into a view class
that's it
then you can instanciate the class :)
class JoinServerUI(ui.View):
def __init__(self, timeout: int = None):
super().__init__(timeout=timeout)
@discord.ui.button(label="join", style=discord.ButtonStyle.green)
async def join(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_message("Test")
Then just send a message and write :
interaction.response.send_message(embed=embed_join, view=JoinServerUI())
:) @whole shoal
OHH
btw label should be in lowercase
discordpy do not specify this in their errors because dumb error management :(
content
Yah no it's the same error
no dms please
what would be better
check in the sql statement if it is alike or check it in the autocomplete?
what do you mean
I can do
def get_similarities(self, check: str, limit: int = 20):
result = self.c.execute("SELECT name FROM tags WHERE name LIKE %?% LIMIT ?", (check, limit))
return result.fetchall()```
or do smt like this
**@fruits.autocomplete('fruit')
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
return [
app_commands.Choice(name=fruit, value=fruit)
for fruit in fruits if current.lower() in fruit.lower()
]**```
probably better to do in autocomplete
is there a limit for autocomplete optoins?
k nvm
The coroutine decorator must return a list of Choice objects. Only up to 25 objects are supported.
I personnaly just use Literal x)
like : Literal["banana", "pineapple" etc]
and it works just fine for me
i don't think that's how it works
[] uses the indexing syntax
() would be calling a method or class
you can handle [] as you want
I think
idk how to search it
if you wanted to define the choices as a list, you could use the choices() decorator instead
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.choices py @app_commands.command() @app_commands.describe(fruits='fruits to choose from') @app_commands.choices(fruits=[ Choice(name='apple', value=1), Choice(name='banana', value=2), Choice(name='cherry', value=3), ]) async def fruit(interaction: discord.Interaction, fruits: Choice[int]):
oh
didn't meant that
I can't do that as the values may vary
then what were you referring to by "making it" a list/tuple?
as I said you can still make it easier
by using Literal
i know, im just asking them specifically what they meant
yo can actually just write :
@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
async def fruit(interaction: discord.Interaction, fruits: Literal['apple', 'banana', 'cherry']):
oh ok sure
they implement __class_getitem__
hmm
btw I really love your website it's pretty original
I actually came on it by accident
ty <3
you mean like literally writing a list/tuple as the annotation? literally you can, but literal[] is the literal standard defined by pep 586 so type checkers will literally hate you for not using literal
I am having issues with the spacingin my pc it looks like this
I was gettting a weird socket error
@edgy zinc
from what ?
from the flask app
yes ?
so the problem is in style not logic ?
yeah
go on the server I have in my description to not get the people from here angry because ouuuh against the rules to talk off topic
Hi



