#discord-bots
1 messages · Page 208 of 1
The answer is yes
@slate swan :x: Your 3.10 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'commands' is not defined
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
@slate swan :x: Your 3.10 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named 'discord'
does anyone know how to make a button and detect who pushes it?
No, like the line should match colour with embed’s background not discord’s background (sorry I’m replying late)
and discord.Colour.dark_embed didn’t work for me when I tried doing it
Yeah this didn't work, as it is a cog it needs to derive from cogs which view doesn't.
nvm got this working ty for your help
isnt it?
hey i can make a new help command
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
my command help is not in that
!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.
to your bot constructor pass help_command=None
client.remove_command("help")```
will it work?
depends where you put it but should work
works
||~~lmao 90% code is completed||
hey i dont have database so is it ok to store information in text file? @slate swan
``
I am trying to create an embed reaction role post with buttons wthin a cog but I am not sure how to approach the interactions now, so when the button is clicked, you either get the role or remove it depending if you already ahve it or not. Just wondering if anyone could advise, heres my code: https://paste.pythondiscord.com/xizifilazi
I did get adv ice from mudkip last night, which they did advice to subclass the buttons and views, like so https://paste.pythondiscord.com/avegifegux aswell as add in a persistent view with a call back for the buttons, but I just wasn't able to get this working as the error last night just said cogs must derive from 'Cog'. Which is understandable, as "each cog is a python class that subclasses commands.Cog."
what information
i am creating a lottery system
well better way would be to use json file if its not too much data
hmm i was thinking of that only or probably i should switch to mongo db
mongodb is a good choice
as of now a line is added at last and my bot selects sometimes that blank space
thats not how to send emojis via discord bot
You need to do <:emojiname:emjiid>
If they are custom you can do to any channel in your discord server /:emoji: and it will give you what you need.
you need something like this !this
.pop() doesnt works well
!this
put backslash before emoji
and you get the form you can use in discord bot
Oh back slash not front slash, sorry.

you can do it yourself
thats why you should use mongodb
choose emoji you want to send and put backslash before it then send
thats front slash
back slash, you also need to make sure those emojis are in the server the bot is in.
If the emoji isn't in this server, or even your own server, it won't work
do it on the server where the emojis are at
ahh i guess now i need to work more for that
Show the code then
not here cause you dont have nitro
mondodb is document type database
so you store json objects in it
You can't use emojis in field names
: (
do you know what that means?
And why are you saying it's not working?
Because you can't use it there
No markups in field name
what?
{
"id": 12345,
"text": "simple message"
}``` this is example json
i know that lol
works like dictionary in python
i also worked on js and json before
And???
good so you need key: value pairs in mongodb
I'm saying that you can't use custom emojis in field names
so you can access data via key
wait how will i store only id of members?
in json
It's in the embed description
depends how you want to use it
i assume you want to have a list of members who can/cant do something
then you could do json { "canDoSomething": [ 123, 456 ] }
which one is good?
?
iirc below you should pick a city where server will be pick the onle closest to you look where is that
Hello, a query:
When someone puts a bot to their server and does not give you all the permits you need to work well, in console ends up giving a permit error, which I can use so that the error in console does not jump.
"For error related to user permissions I use:"
@client.event
async def on_command_error(ctx,error):
isinstance(error,command.MissingPermissions):
em = discord.Embed(description=f'*💬 No tienes permisos para usar este comando*', color=0x2c4763)
await ctx.send(embed=em)
Doesn't really matter for discord bots, on location. But all 3 are fine, just make sure to understand what is free and what isn't and bare in mind all 3 free tiers do expire after certain amount of time.
right my bad for a discord bot the location actually doesnt matter allthough closest to discord servers the bot will be faster
!d discord.ext.commands.MissingPermissions.missing_permissions
The required permissions that are missing.
commands.CommandOnCoooldown
cause this shouldnt have the / inside
!this
what autocorrects
okay but it shouldnt have the / inside
remove it
then paste it inside codeblock
i have connected mongodb to my discord bot now i want to write user id of user in db
how to do that? also can i make multiple collections?

can i do what
?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
did you connect to mongo in code already?
I was wondering if anyone could potentially help with my query 🙂
No
It doesn't understand UI stuff from discord.py
And pretty much useless even how much you try to ask it
Plus its awful, I am not going to use that crap lol.
As you shouldn't
dont
bruh whats wrong
?
?
just explain it
Im not even gonna try guessin
alr gotcha
Show the code instead and use paste.pythondisord.com to send the code.
u talking about the <member...>
Quite frankly what I am looking at, <:member1-1:ID> that specific emoji is either named wrong, or doesn't exist on the server.
await fetch_emoji(emoji_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.
Note
This method is an API call. For general usage, consider iterating over [`emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.emojis "discord.Guild.emojis") instead.
Changed in version 2.0: `emoji_id` parameter is now positional-only.
you can simply bot.get_emoji(ID)
interesting
so these are unique?
across guilds?
Emoji IDs? yeah
<:member1~1:1081933618080911362> if the name is correct, then the ID must be wrong. Have you double checked the ID?
every snowflake is unique
mh
Bot has only get_emoji
since it utilise cache
Guilds have fetch_emoji
since the request is bound to a guild
though it wouldn't hurt to add both methods to either
"Discord utilizes Twitter's snowflake format for uniquely identifiable descriptors (IDs). These IDs are guaranteed to be unique across all of Discord, except in some unique scenarios in which child objects share their parent's ID."
Are you actully getting the emoji id or are you getting the message id?
just type the emoji out in chat then copy it to the clipboard and send it but with a backslash in front of it
Sounds to me you are post it, then copying the message ID itself.
people do that often lol^
\emoji
you need to do back slash:member1~1: and it will give you the unique snowflake (emoji name and id)
!this
This is really only required for custom emojis as far as I am aware, take note of it so you dont forget in the future 🙂
Its one way to do it.
you don't need to fetch emojis just to use it
hello who can help me please
i got this problem and idk how to fix it
require('discord.js-selfbot-v13');
How can I make it where someone can pass a channel as a argument and it'll convert it to a channel_id ?
oh ok
How do I make the buttons expire immediately after the button is clicked
lmao, its a py server
yes
thats easy. channel.id
no
how to fix
self bots are illegal at first place
Correct answer is to do channel = discord.TextChannel, then you can do channel.id
if u know then why asking bruh
Someone else helped me lol?
plus, as you said argument, I know u have defined the variable channel, so I said the finishing
what?
impossible on repl
I literally asked how can I make it where someone can pass a channel as a argument
ok, I am dumb
why are you using replit
no
cuz yez
i think you mean channel: discord.TextChannel
sublime text make me cancer
then install another editor
who said anything about IDLE
yep
vscode uses up more ram
vim is also good but it's not user friendly and takes time to learn
Notepad ++ is good, I use to use that as a lightweight alternative when I originally started coding.
Just set using their UI
If your only using it to edit files and not adding lots different extensions, VSC should also be fine.
Yeah that's what I meant
no idea why I made it a variable though
the colon makes it an annotation
You're passing a invalid token
Read the error
I mean tbf they most likely did and just don't understand what's it's being caused from
`PS D:\CODE\DEAR GOD HELP US> & 'C:\Users\Admin\AppData\Local\Microsoft\WindowsApps\python3.10.exe' 'c:\Users\Admin.vscode\extensions\ms-python.python-2023.4.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '58380' '--' 'd:\CODE\DEAR GOD HELP US\bot.py'
2023-03-05 22:02:51 INFO discord.client logging in using static token
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py",
line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py",
line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\CODE\DEAR GOD HELP US\bot.py", line 18, in <module>
client.run(os.getenv('TOKEN'))
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete return future.result()
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 612, in login
data = await self.http.static_login(token)
File "C:\Users\Admin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py",
line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc`
i use cmd before
Hey @lunar charm!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
`import discord
import os
client = discord.Client(intents=discord.Intents.default())
@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
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))`
that's not what i meant, you have to have python read it
it's not actually set as an environment variable immediately
!pypi dotenv
!pypi python-dotenv
uhh
from dotenv import load_dotenv
you still have to install it though
but you gave him links to install
so i sent code
ok
` note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.`
egg_info did not run successfully.
did you use my package?
Hey @lunar charm!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i tried pip install dotenv
it's pip install python-dotenv
that's a different package that you're trying to install
this wont work
oh its works
call the method
load_dotenv()?
sure, before you use your environment variable
where should i put it
after imports
how do I make those buttons expire after the button interaction is successful
why dont u use react system
because buttons are better in every way
thats old
!d discord.Button.disabled
Whether the button is disabled or not.
inside the button class or inside the app_commands?
inside your button callback
ok
so you want it so that when one is clicked, the rest disable?
yes
yes
ok
you could just loop over all of the buttons
for item in view.children:
if isinstance(item, discord.ui.Button):
item.disabled = True
inside the callback
@discord.ui.button()
async def idk(self, interaction: discord.Interaction, button: discord.ui.Button):
self.stop()
sure
u could this, it stops after a single click
that doesn't disable the buttons though
class MyView(discord.ui.View):
@discord.ui.button(label="Rock", style=discord.ButtonStyle.green)
async def rock(self, interaction: discord.Interaction, button: discord.ui.Button):
computer_choice = ['Rock', 'Paper', 'Scissors']
computer_choice2 = random.choice(computer_choice)
if computer_choice2 == 'Rock':
await interaction.response.edit_message(content='Draw! I and you chose `Rock`.')
elif computer_choice2 == 'Scissors':
await interaction.response.edit_message(content='You win! I chose `Scissors` and you chose `Rock`!')
else:
await interaction.response.edit_message(content='I won! I chose `Paper` and you chose `Rock`!')```
my code is like this
the user has no way of knowing it's disabled
Stops accepting the click...
tru
if it's disabled the user can't click in the first place
just make a helper function named stop which has something like this:
def stop():
for item in self.children:
if isinstance(item, discord.ui.Button):
item.disabled = True
super().stop()
then you can call stop() whenever
async def stop() right
wherever
it doesn't matter
probably after the button has been clicked
if you have a tie, you probably don't need to stop it
nah I want to stop it everywhere
then do that
don;t you need to edit the message and set message's view to self for the disable thing to happen
hey what?
yeah you will probably need to update it i guess
so the view?
client=commands.Bot(command_prefix='z',bot=True,help_command=False,intents=discord.Intents.default())
does this command clear?
what
help command = False?? 
there's no bot= kwarg is there?
so its true?
if u dont want a help command set it to None
making a help command is not true or false
it's asking you to supply a help command for use
k
discord.errors.LoginFailure: Improper token has been passed.
💀
ive changed my entire code and try new token
send the first and last few characters of your token
MTA4MTkz...C7gFgrJ54g
yez?
you have quotes around it
remove it?
yes
still there
what does your code look like
`import discord
import os
from discord.ext import commands
import dotenv
from dotenv import load_dotenv
client=commands.Bot(command_prefix='z',sbot=True,help_command=None,intents=discord.Intents.default())
@client.event
async def on_ready():
print('online')
client.run(os.getenv('TOKEN'))`
are you sure your token is valid and works?
i just create it 💀
you cant connect to the bot gateway with your user token pal
what is sbot
random name
you didn't even run the load_dotenv function @lunar charm
and you don't need to do import dotenv when you've already imported the function
bro 💀
i gave u token cuz ýe
just a name
check if that token is legal
i've already said whats wrong
here
and also remove the extra import
and sbot part
Thank you
good
@bot.command()
async def test(ctx):
await ctx.send("ephemeral", ephemeral=True)
I tried this code and upgraded discord.py library. Why isn't it working
Only for interactions
ctx
!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.
its only for slash commands
alright, and do I need a verified bot for slash commands?
No
Hi :)
Hi 🐈
help

.
@discord.ui.button(label="Join now only 5₹", style=discord.ButtonStyle.green)
async def join(self, interaction: discord.Interaction, button: discord.ui.Button ):
#if the user's id is in the text file then send a message
if interaction.user.id in requested.find_one():
return await interaction.response.send_message("You have already requested once.", ephemeral=True)
else:
requested.insert_one({"_id": interaction.user.id})
await interaction.response.send_message("Please check your DM", ephemeral=True)
await interaction.user.send("Please pay to pritish384@fam(testing)")
channel = client.get_channel(1081859510148276224)
await channel.send(f"{interaction.user.mention} has requested to join the lottery. check the payment and then add them.")
what is the problem in code?
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: database.requested index: _id_ dup key: { _id: 921314333567352862 }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 921314333567352862}, 'errmsg': 'E11000 duplicate key error collection: database.requested index: _id_ dup key: { _id: 921314333567352862 }'}
are you using pymongo?
I've never used that before but i would guess that you're trying to insert a user id into the database in a unique field while it's already in there
don't set _id
that's mongodb's internal id

pymongo is sync u need motor
yep
use motor
how to do that
@commands.command()
async def unban(self,ctx, member:nextcord.Member=None):
if member == None:
em1 = nextcord.Embed(title="__**Unban Error**__",description="Member not found! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em1)
if member.id == ctx.author.id:
em2 = nextcord.Embed(title="__**Unban Error**__",description="You can't unban yourself! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em2)
def check_author(m):
return m.author.id == member.id
await member.unban(check=check_author)
em5 = nextcord.Embed(title="Unban Success", description=f"{member.mention}({member.id}) Got unbanned!", color=nextcord.Color.green())
await ctx.reply(embed=em5) ```
and when doing !unban <id> it says that the member didnt found
because the member isnt in the server
Typehint as user instead
user.unban?
2023-03-05 22:11:06 ERROR discord.ui.view Ignoring exception in view <lottery timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Join now only 5₹' emoji=None row=None>```
guild.unban
ill try ty
@commands.command()
async def unban(self,ctx, member:nextcord.Member=None):
guild=ctx.guild
if member == None:
em1 = nextcord.Embed(title="__**Unban Error**__",description="Member not found! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em1)
if member.id == ctx.author.id:
em2 = nextcord.Embed(title="__**Unban Error**__",description="You can't unban yourself! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em2)
def check_author(m):
return m.author.id == member.id
await guild.unban(check=check_author)
em5 = nextcord.Embed(title="Unban Success", description=f"{member.mention}({member.id}) Got unbanned!", color=nextcord.Color.green())
await ctx.reply(embed=em5)
still same error
where's user
you can't use member
user=member?
no'
wdym why
typehint it as user
okay
@commands.command()
async def unban(self,ctx, user:nextcord.Member=None):
guild=ctx.guild
if user == None:
em1 = nextcord.Embed(title="__**Unban Error**__",description="Member not found! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em1)
if user.id == ctx.author.id:
em2 = nextcord.Embed(title="__**Unban Error**__",description="You can't unban yourself! :x:", color=nextcord.Color.red())
return await ctx.reply(embed=em2)
def check_author(m):
return m.author.id == user.id
await guild.unban(check=check_author)
em5 = nextcord.Embed(title="Unban Success", description=f"{user.mention}({user.id}) Got unbanned!", color=nextcord.Color.green())
await ctx.reply(embed=em5)```
user: nextcord.User
didnt know that was a thing
await guild.unban(check=check_author)
TypeError: unban() got an unexpected keyword argument 'check'
if check isnt an option then
you cant do that, just guild.unban(user)
oh
async def check(ctx, user: discord.User):
if user.id in enrolled.find_one():
return await ctx.send("User is already present")
not working
oo thanks!
give code
imagine not using cogs
bro use cogs for gods sake
i enjoy that you think that is the issue
nvm
Guys, I am dying with this code: https://paste.pythondiscord.com/kahajedozu
The issue is that the buttons are not getting disabled after a button interaction is successful
it is driving me crazy for 3 hours straight
are u updating the view?
yes
any specific error?
nothing in the console
the msg is updated but the buttons are not disabled
discord.utils.logging()
have you tried printing the components after disabling them to make sure they're actually being disabled
discord.utils.setup_logging()
I debugged them
I did that already in the loop man
the button from the functional parameters
cogs doesn't necessarily mean file, he could have used cogs you don't know that
i don't use cogs, prefer doing everything low level
why discord's skill issue is destroying my life
I guess I need a break
this thing is limiting my brain for 3 hours straight
if you're printing the buttons and they're disabled then it's not editing them
the buttons are never disabled 
cogs aren't high level they're just a means of organizing code
the buttons are not disabling even if the interaction is expired, tell me what do I do? Jump from the window? I am disgusted
you should separate your game logic and discord code i think @dull terrace
since you are making an RPG
it is pretty seperated
i have like 30 files or something rn 
embed.set_author?
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
!d discord.Embed.set_author
is that wakatime or something
oops
just a plugin for vscode
that's cool
tbh, I dont know why author exists lol
you should check out wakatime i signed up for it recently
link?
for crossposting
i use wakatime
very cool
i know
call the function
whats wakatime O.o
i already linked the docs
it's here
displays your coding stats, the projects u worked on, the languages, for how long, etc
and you just call it like any function, embed.set_author(name = ...)
what does the *_ do in your username
last.fm for coding basically
positional arguments
no, that's not for calling the function that's just part of the function signature (its definition)
the !d command in the bot doesn't show how to use the function, it shows how it's defined
!e ```py
def foo(*):
print()
foo(1, 2 ,3, 4)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
(1, 2, 3, 4)
packs the positional args
ohh it's just the useless placeholder thing
for variables you don't care about
it's not don't care about, just don't need
that's what i learned anyway, you use _ when unpacking stuff as a variable for things you dont need
it's not really something you should use in your code
why not, i've used it a couple times
yeah the *_ is forsure meant to ignore the usage
but * is not at all useless
@quick gust i changed it
yeah the combination made me think it was doing something special for some reason
still doesnt show. waka time right?
can someone finish this bot update for me
markdown editor and notes app ❤️
i use it for keeping track of everything though
nice
Ya'll keep track of stuff? Dang
track of what?
what are you guys tracking?
daily stuff
not me i don;t even know what im doing 90% of time
🫂
just life stuff and things that need to be organized
the only thing i look at is lines of code so i can remind myself im actually progressing
Portal series 👀
0%

this thing looks like github commit graph but empty 😔
off-topic but i haven't figured out how to display the percentage yet, if you guys know a good game tracking api let me know lol
Steam.....?
Idk if they got an API tho
0 second daily average
but it's not cross-platform
@client.command()
async def check(ctx,user: discord.Member):
for x in requested.find():
if x["_id"] == user.id:
await ctx.send("User is in the database")
else:
await ctx.send("User is not in the database")
i am getting output 2 times
Hi all, finally got my code working so can use buttons etc, just struggling with getitng my persistent view work now, was wondering if someone could run over my code and see if I am doing it wrong, I did take a nosey at the examples in GitHub but as they are single instance bots where as I am within a cog, it does't really give me the best examples:
https://paste.pythondiscord.com/nusekobihi
Just need the view to stay persistent, so when I shut down the bot and reboot it, the embed can still use the callback function to get roles without constantly having to run the command to post a new one.
why for loop?
it was showing discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: index '_id' cannot be applied to Cursor instances
then i took code from stackoverflow it worked but it shows 2 times there are 2 ppl in my database
@client.command()
async def check(ctx ,user: discord.Member):
x = requested.find()
if user.id in x["_id"]:
await ctx.send("User is in the database")
else:
await ctx.send("User is not in the database")
now?
don't use _id i've already said that
why
user.id == x["_id"]
"_id" stores an integer right?
yep
remove those database entries and use id instead of _id
also you should use motor not pymongo
No please don't
id is an in built function
@client.command()
async def check(ctx ,user: discord.Member):
x = requested.find_one({"id":user.id})
if user.id == x:
await ctx.send("User is in the database")
else:
await ctx.send("User is not in the database")
i did this
how can I set color in embed using embed variable instead of kwargs
so??? this isn't even python related at all
what do you mean embed variable
embed.color = ...
yes this one
embed = discord.Embed(
title="Create Your Profile",
description=(game_description),
color=0xBB8FCE
)
I use this within my embed.
why do you have paranthesis around game_description?
I don't want to use color here for some reasons
Its a string variable. It just look neater pulling it out of that block and setting it as its own variable.
yes but why these ( )
doesn't really matter, for me it just helps not to get confused with other values.
does someone know hoy to delete a channel with the bot????
!d discord.GuildChannel.delete
No documentation found for the requested symbol.
!d discord.abc.GuildChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Basically I get this error and I dont understand why
This is my script : https://paste.pythondiscord.com/uqobekemic
[2023-03-05 14:43:03] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\matis\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(args, kwargs)
File "c:\Users\matis\Desktop\ModMail GIE\main.py", line 100, in on_message
await channel.send(f"{ctx.author}({ctx.author.id}):* {ctx.content}")
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'
try:
# Tries to get the channel
channel = bot.get_channel(opened_ticket[1])
except:
# Oops! Channel doesn't exist but they're in the database?
get_channel doesn't raise an error
if the channel isnt in cache
it just returns None
you should use if statement rather than try-except
so
I should get rid of except and replace try by if?
yeah that's the problem. It gives me an error when dming the bot
it doesnt even send the confirmation embed
instead of pinging random people, you can claim a help channel: #❓|how-to-get-help
I get this error when I dm the modmail bot,
error: [2023-03-05 15:14:26] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\matis\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(args, kwargs)
File "c:\Users\matis\Desktop\ModMail GIE\main.py", line 100, in on_message
await channel.send(f"{ctx.author}({ctx.author.id}):* {ctx.content}")
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'
my script: https://paste.pythondiscord.com/baxivigiga
IM A BEGINNER BTW
don't ping random people
can you see what opened_ticket[1] equals
@commands.command()
async def duel(self, ctx, user = discord.Member):
# eq.execute("""SELECT user FROM crown""")
msg = await ctx.send("test")
await msg.add_reaction("\U00002705")
if str(msg.emoji) == '\U00002705' and msg.user_id != 1002921149795143680:
if msg.user_id == user.id:
print("works")
```How would I reference msg's reactions?
!d discord.ext.commands.dm_only
@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly "discord.ext.commands.PrivateMessageOnly") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
New in version 1.1.
It makes commands only work in DM's right?
How many characters is it?
The limit of characters in an embed field is 1024 characters
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Wdym
https://paste.pythondiscord.com/ahufahiheg I was wondering if someone could take a snoop over my code and advise as to what I can do to get the view persistent, as currently, if I restart the bot, the buttons stop working.
- the view must have a timeout
- all view items must have a custom_id
- you must add the view in your bot's setup_hook
class DiscordBot(commands.Bot)
async def setup_hook(self):
await self.add_view(ReactionRoleView())
it has a timeout set to none, I'll take a look into this custom_id now, and its in a cog not the bots main file, would this still apply?
if it's in a cog i guess you can just override cog_load in the cog
How do I make the print say Logged in as bot#0001 without saying the bot's username and tag. Here's my code
async def on_ready():
print("Logged in")```
????
how do you make the print say the bot username and tag without saying the bot username or tag??
logged in as the bots username and tag
yes i think self.user or something i tried but didnt work
bot.user or self.bot.user
oh okay thanks
just do str(bot.user)
where'd you get self from though
if hes in a cog
i hate making views with state
so annoying why does the view system have to be like this
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that it does a sticky message instead of resending? My script is: https://paste.pythondiscord.com/yidukekala
ctx in on_message 
what does opened_ticket equal??
@dense jackal
@dense jackal also, don't connect to your database each time you want to query something, you should have one shared connection
the server has two factor moderation enabled
Enable your own
actually i'm not sure, it might be the bot owner's 2fa
Aight so what do I do now
Wdym by that
connect to the database once and store it as a variable
I did that script with a friend im not that good on coding
and then reuse that connection
sorry i cannot right now, maybe ask in #databases
A friend coded most of the things. Anyways @slate swan I dont have anymore errors rn
venad coded it?
Yep, it always used to connect twice
that's not good...
two functions are competing to write to the database file
that's how you get corruption
sure
Ty
How could I fix this error?
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\http.py", line 400, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Command name is invalid
Eagle Bird GPT (Dev)#2353 is now online!
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 199, in on_application_command_error
embed.add_field("time:", value=datetime.datetime.now)
TypeError: Embed.add_field() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
embed = nextcord.Embed(title="Error!", description={error}, color=nextcord.Color.red())
embed.add_field("time:", value=datetime.datetime.now)
embed.add_field("server:", value=interaction.guild.name)
embed.add_field("User:", value=interaction.user.mention)
embed.set_thumbnail(url="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgyNvusWhOvc1NUEL5SwDFHzab9ISQ495SJpo_UT-BzzbYX-5B3VbcfH20-rZ4QBjbsiE&usqp=CAU")
channel = bot.get_channel(1066505917929111587)```
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
Ok
and just to double check
keywords are things that are in the async function?
@naive briar
No
What is it then? I kinda forgot
!kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
• Decorators (see /tag decorators)
• Inheritance (overriding methods)
• Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
• Flexibility (writing functions that behave like dict() or print())
See /tag positional-keyword for information about positional and keyword arguments
Sheesh, not that
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• /tag param-arg (Parameters vs. Arguments)
I guess that's a bit better
the tag should also talk about / and * tbh
You're an anime girl now?
!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.
yez
How does logging work in 2.0? It says that the logger is now built-in the documentation.
Hello guys, from yesterday, if you remember, I had an issue with buttons which is solved
The setting up logging page seems to be detailing logging for pre-2.0 discordpy.
ok
Hello, so my code connects to a game hoster. it downloads the logs and then i parse them.
for some reason i keep getting the error:
I/O operation on closed file.
Any clues to what im doing wrong? am i closing the file in the wrong section?
https://paste.pythondiscord.com/orabofamuf
Full traceback, please
@sick birch Im not getting anything. it's on a loop and then it just continues?
Ahh i see, any ideas how i can improve it?
raise error instead of print(error) for now but you should probably get that fixed later
Still the same, with raise error
Your console should spit out a better error message, no?
No, exactly the same still :/
847327487058247712 2023.03.06 04:31:57 76561198296269130 jMarchinton 2 Local test
GUILD: 847327487058247712 - Player: jMarchinton 'test'
I/O operation on closed file.
[20:32:08] Checking for new log files.
--------------------------------------------------------------
[20:32:28] Checking for new log files.
--------------------------------------------------------------
[20:32:49] Checking for new log files.
--------------------------------------------------------------```
Hiring someone to make a discord bot for me. DM if interested!
Payment is upon completion, USD only (cash app or paypal)
this server is not for paid work
oh
@hushed galleon can I ping you tomorrow to continue this conversation? Its getting late and I really gotta go
keep a dictionary of users to their ticket views and look in that to see if a user has one still running
the idea is sessentially: ```py
ticket_views = {}
After sending a view, store it in dictionary using the member (or ID) as the key:
await message.channel.send(..., view=ticketbuttons)
ticket_views[message.author] = ticketbuttons
When checking to create a ticket, see if they have an older view in progress:
old_view = ticket_views.get(message.author)
if old_view is not None and not old_view.is_finished():
... # tell them no or something```
Oh
i might not be available tomorrow but you can link back to this and your initial question as context for someone else to help
Alright thank you!
Tell me how to use thread in discord.py
what if I'm using like :Giveaways: ?
You should be able to, but better to use full format like !this
how the heck do i get that?
i'm confused
how do i get that format because it is not working for me
raceback (most recent call last):
File "/var/lib/pufferpanel/servers/52aa6b86/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/var/lib/pufferpanel/servers/52aa6b86/cogs/Kingdom.py", line 82, in react
await react_messasge.add_reaction(emoji=":Giveaways:")
TypeError: PartialMessage.add_reaction() got some positional-only arguments passed as keyword arguments: 'emoji'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/var/lib/pufferpanel/servers/52aa6b86/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/var/lib/pufferpanel/servers/52aa6b86/.local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/var/lib/pufferpanel/servers/52aa6b86/.local/lib/python3.10/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: PartialMessage.add_reaction() got some positional-only arguments passed as keyword arguments: 'emoji'```
@commands.command()
async def react(self, ctx):
message = discord.Embed(title=f'**Reation Roles**', description=f"<@&1081509778045550592> - :Giveaways: \n <@&1082155989324791898> - :Drops:")
react_messasge = await ctx.send(message)
await react_messasge.add_reaction(emoji="@commands.command()
async def react(self, ctx):
message = discord.Embed(title=f'**Reation Roles**', description=f"<@&1081509778045550592> - :Giveaways: \n <@&1082155989324791898> - :Drops:")
react_messasge = await ctx.send(message)
await react_messasge.add_reaction(emoji=":Giveaways:")
#Note all ids are not vaild```
the error i get
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
All arguments before / are positional-only
And you are providing emoji as keyword argument
I'm confused what positional-only means as I have never seen it
Opposite of keyword
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• /tag param-arg (Parameters vs. Arguments)
so how do i write it?
add_reaction("thing")
oh ok thank you
can anybody send me material about how to make mass dm bot?
we dont help with malicious projects here
what do you mean mass dm bot isnt that against tos?
Oh I am sorry
Then can anybody send me screen record of mass dm bot working? I only need screen record.
Huh?
Bro read channel description
We dont do that here
yes sir
What is client.say() in discord.py?
What does @client.command(pass_context = True) mean?
What does @client.command(pass_context = True) mean?
than what was the meaning of pass_context?
Whether to pass ctx argument to function
await client.send_message(member, content)
await client.say("DM Sent To : {} ✅ ".format(member))
what is send_message?
difference with send?
just use send
instead say and send_message?
send_message it's for interactions
Which year is this
bot
@commands.has_permissions(kick_members=True)
async def userinfo(ctx, user: discord.Member):
r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1))
embed = discord.Embed(title="{}'s info".format(user.name), description="Here's what I could find.", color = discord.Color((r << 16) + (g << 8) + b))
embed.add_field(name="Name", value=user.name, inline=True)
embed.add_field(name="ID", value=user.id, inline=True)
embed.add_field(name="Status", value=user.status, inline=True)
embed.add_field(name="Highest role", value=user.top_role)
embed.add_field(name="Joined", value=user.joined_at)
embed.set_thumbnail(url=user.avatar_url)
await client.say(embed=embed)
can u help me make it into updated one?
Docs can for sure
I am new to python
which part do I have to update in my code above?
Man
For learn-fix something you need to read-understand
The guild that the message belongs to, if applicable.
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e @bot.command()
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, arg):
logsChannel = bot.get_channel(1077469152761094255)
user = member.mention
embed = discord.Embed(title="Warning issued: ", color=0xf40000)
embed.add_field(name="Warning: ", value=f'Reason: {arg}', inline=False)
embed.add_field(name="User warned: ", value=f'{member.mention}', inline=False)
embed.add_field(name="Warned by: ", value=f'{ctx.author}', inline=False)
message = await ctx.send(embed=embed)
@calm sapphire :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
!e @bot.command()
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, arg):
logsChannel = bot.get_channel(1077469152761094255)
user = member.mention
embed = discord.Embed(title="Warning issued: ", color=0xf40000)
embed.add_field(name="Warning: ", value=f'Reason: {arg}', inline=False)
embed.add_field(name="User warned: ", value=f'{member.mention}', inline=False)
embed.add_field(name="Warned by: ", value=f'{ctx.author}', inline=False)
message = await ctx.send(embed=embed)
@calm sapphire :x: Your 3.10 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
@client.command()
async def send(ctx):
print(ctx.message.guild.members)
when I run this expression using bot, only bot is displayed. why?
Whether guild member related events are enabled.
This corresponds to the following events...
lol
Then to get all members above, what do I have to do?
i cant figure out how to make a working welcome message
Enable the members intent
How?
Quite easily
how
without cogs or database?
intents = discord.Intents.default()
intents.members = True
🤷
If you wanna have separate messages for guilds, you would have to use db of course
Cog are just a method of code organisation
one message
for all
Then it is as simple as that
thx
then what
@client.command()
async def send(ctx, *, content: str):
for member in ctx.message.guild.members:
try:
await client.send_message(member, content)
When I run this command, it doesnt work
Just ping everyone in your server, what's the point of mass DMing
try to test "await client.send_message(member, content)"
client.send_message(member, content)
what does it mean?
Who told you to "try to test" 🧐
btw, client.send_message(member, content)
what does it mean?
Why are you trying to use it while you don't t even know what it means
And it doesn't even exist
People here have already told you
i need help with my ticket command
okay
!e None.edit
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'edit'
Read the error
ye?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Command.__call__() missing 1 required positional argument: 'context
Is it possible to change the bot’s username with just the token
Yes
Send the code along with it
def __init__(self):
super().__init__(timeout=60.0)
self.value = None
@discord.ui.button(style=discord.ButtonStyle.green, label="Yes", emoji=":CHECK_CHECK_1:")
async def yes(self, button: discord.ui.Button, interaction: discord.Integration):
self.value = True
self.stop()
@discord.ui.button(style=discord.ButtonStyle.red,lebel="No", emoji=":CHECK_CROSS_1:")
async def no(self, button: discord.ui.Button, interaction: discord.Integration):
self.value = False
self.stop()
if __name__=="__main__":
bot = MyBot(command_prefix="-", intents=discord.Intents.all())
# MESSAGE COMMANDS
@bot.command()
async def Prompt(ctx):
view = Prompt()
await ctx.send("Do youwant to continue?", view=view)
await view.wait()
if view.value is True:
await ctx.send("You said yes!")
elif view.value is False:
await ctx.send("You said no!")
else:
await ctx.send("You didn't answer in time.")```
Why is there a bot command inside a view
How
Look at it better it's not
He's just a got really bad way of writing it
Full traceback
?
await msg.edit(f"Ticket created successfully! {channel.mention}")
@naive briar
What?
what is wrong wit my code
await msg.edit(f"Ticket created successfully! {channel.mention}")
AttributeError: 'NoneType' object has no attribute 'edit'```
so how do i fix
Make it an message object?
msg = await interaction.response.send_message("A ticket is being created...", ephemeral=True)
Useless telling someone to read it if they don't know anything about what they're even doing and just using copy pasted code
!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.
The meth doesn't return the sent message, read the docs
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
Use that
You can't use the interaction response that has already been used
!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.
im not
the edit message isTicket created successfully! {channel.mention}"
the first is A ticket is being created...", ephemeral=True)
?
@slate swan NameError: name 'edit_original_response' is not defined
Did you read what I sent? It's a method of Interaction object
i used this
NameError: name 'edit' is not defined
@naive briar NameError: name 'edit' is not defined
!e
print(not_defined)
@shrewd apex :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'not_defined' is not defined
edit = ("Ticket created successfully! {channel.mention}")
u have to assign the message to a variable
what do i define it as
@shrewd apex
?
so?
?
@shrewd apex @naive briar @slate swan
Bruv stop pinging
i need help
Then wait until someone wants to help
cant u help
No
@calm sapphire if I may ask, what is your python knowledge level
im trying to edit the button.emoji using wait_for reaction, when the user add the reaction i want the bot add this emoji to button.emoji
Traceback (most recent call last):
File "\discord\ui\view.py", line 427, in _scheduled_task
await interaction.response.edit_message(view=self.view)
File "\discord\interactions.py", line 898, in edit_message
await adapter.create_interaction_response(
File "\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
By using response.edit_message, you are responding to interaction, but you already responded to it with response.send_message, you need to edit original response
Dunno what's the method for that in dpy
!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.
This
Actually wait
Why did you remove that send_message line from code
At that point you are not responding to interaction at all
Use interaction.response.send_message instead of interaction.channel.send
then how i will use wait_for to interaction.response.send_message ?
You should be able to get the response message
!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 "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "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.
discord.ext.commands.errors.CommandNotFound: Command "echo" is not found```
pls fix this error i am getting since i convert my bot commands and events to cogs
How are we supposed to help you if we dont know the code
what is the right event for button click
i need help using replit
Channels list in slash command how?
discord.TextChannel
Thank you
Send the error thats coming
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Discord Bot\BotToken.py", line 69, in on_ready
for key, value in os.environ.items:
TypeError: 'method' object is not iterable
can anybody help me solve this error?
.items(), it's a method
i get this AFK command from chatbot, i don't know where the problem the bot didn't auto reply when AFK user mentioned
@client.event
async def on_message(message):
c_afk = False
if c_afk and not message.content.startswith('!'):
reason = c_afk.get(message.author.id, None)
if reason:
# Send an auto-reply
reply = f'{message.author.mention} is AFK. Reason: {reason}'
await message.channel.send(reply)
await client.process_commands(message)
Is there a bot that has a command to mass role users like
?role @sudden depot
[Long list of discord ids]
Oops sorry whoever I just pinged
It's actually interaction.followup
That's different
Documentation says that to continue interacting with app commands but already used interaction.response must use interaction.followup
He needs the original response message to wait for reaction on it, no additional responses
From what I could see
So interaction.message if the message is waiting for is the same of the response one.
||Must excuse my english||
Only available in component interactions
Not sure if that's a component interaction, I don't remember his problem
I read it and its to edit the button.emoji depending on the reaction that interaction's message gets
Yeah in that case they can use message attribute
Yep
You can do that with dpy
By using FlagConverter class and a simple command.
User select is an option too
Yeah, but to mass role add
So (I think) the best way is to use a Tuple parameter in a FlagConverter class
Discord bot role management not working / Error 403 Even when auth'ed as Administrator, Any kind of role modifications result in a 403 error.
@bot.command(name='mute')
@commands.has_permissions(manage_roles=True)
async def mute(ctx, member: discord.Member, *, reason=None):
role = discord.utils.get(ctx.guild.roles, name="Muted")
if not role:
role = await ctx.guild.create_role(name="Muted")
for channel in ctx.guild.channels:
await channel.set_permissions(role, send_messages=False, speak=False)
await member.add_roles(role, reason=reason)
await ctx.send(f'Muted {member.mention}')
here is the mute code, what are ur suggestions?
!codeblocks
!codeblocks
full cog please
also, is any command working in that cog?
first if statement is always false...
full error traceback?
yes
why do you need it/
you're not showing all relevant code
I am that isn't working
there is nothing else for it
just do as I say please...
have you tried debugging? (checking if the event even gets triggered / ... )
how do i debug it?
the simplest yet most ineffective way is just by printing some stuff in the event
aight, so the on_member_join event does "work"?
yes
everything works
except that
it is triggering
but it's not adding a role
what have printed?
the print line i added in
you'll have to show me, I can't smell code unfortunately
all i did was add this line in both print("role was triggered")
still, you'll have to show me every change you make
that is the change i made
so i know it's triggering
Hi. I'm trying to set an embed image that's being made with Pillow
but the bot ends up sending the image first and then the embed without the image. It's strictly necessary to save the image on disk for this to work? c':
file = discord.File(
result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg"
)
embed = discord.Embed(
title=f"A wild {document['name']} has appeared!", color=0x05E1E1
)
embed.set_image(url=f"attachment://{file.filename}")
await ctx.send(file=file, embed=embed)
it's not
since you like code examples:
@client.command()
async def check(ctx ,user: discord.Member):
x = requested.find_one()
if user.id == x["userid"]:
await ctx.send("User is in the database")
else:
await ctx.send("User is not in the database")
this isnt working well
discord.ext.commands.errors.MemberNotFound: Member "1" not found.
if member not found then send message User is not in the database
how to do that?
full error traceback?
What is x?
what's this supposed to do?
x = requested.find_one()
looks like you're not familiar with getting something from a DB
You're getting this error because the memberConverter couldn't find a member with 1 and you're not catching the error.
i want bot to find the userid in requested collection
if user id is not there send message
@client.command()
async def check(ctx ,user: discord.Member):
x = requested.find_one()
if user.id == x["userid"]:
await ctx.send("User is in the database")
elif user.id != x["userid"]:
await ctx.send("User is not in the database")
this would work ig?
When you pass 1 it tries to convert 1 to Member since it fails it raises an error
it would not
In this case the member does not exists at all so you don't even need to check.
Or at least should
so how do i fix this issue?
can it not find the role?
do as I told you...
send EVERY code change you make in an event, not just "I added this line"
ok
I have a feeling your if statement is never True
how to fix it?
you have 2 options
either you use a global error handler, OR a specific command error handler
I recommend making a global error handler.
that would make sense
i have no error handler rn
does it print any of those?
yes
message wasn't for you
alr, now add this
@client.command()
async def check(ctx, user: discord.Member):
if user.id in requested.find_one():
await ctx.send("User is in the database")
else:
await ctx.send("User is not in the database")
i am trying this
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
print("role was triggered")
guild = self.client.get_guild(payload.guild_id)
if payload.emoji.name == ":Giveaways:" and payload.message_id == 1082332670584950824:
print("got here")
role = discord.utils.get(guild.roles, name="Gw ping")
if role is not None:
print("found role")
member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
print(f"member: {member}")
if member is not None:
await member.add_roles(role)
else: print("else")```
we know, have you read what we told you?
🗿
you're getting a COMMAND argument error, that's something you can't handle in the command itself
it has nothing to do with what's inside your command, your command could be empty, you'll still get the same error
@echo wasp try and see what this prints
