#discord-bots
1 messages · Page 243 of 1
updated original message
It occures when launching discord bot?
yes
Does the bot work after all?
You may want to try updating discord.py to latest version pip install -U discord.py
omfg I was running the bot without the venv

is there any way to wait again cause what if another person clicsk button instead on intended one
?rtfm interaction.wait()
/Cogs/embed.py
@commands.command()
async def testembed(self, ctx: commands.Context, message):
print("called")
if ctx.interaction is not None:
print("Interaction")
else:
print("Not interaction")
``` is there something wrong with this? I've been trying to call this function for a few mins and no luck. I know my bot is identifying the message cause in my main.py I've an on_message callback thats printing my messages
relatable
Could someone help me please.
Traceback
Traceback (most recent call last): File "C:\Users\calcu\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task await item.callback(interaction) File "C:\Users\calcu\Desktop\Python Development\Inner City RP\cogs\commands\set_tickets.py", line 52, in set_ticket ticket = f"{interaction.user.name}-{interaction.user.discriminator}-ticket" AttributeError: 'StringSelect' object has no attribute 'user'
Code:
class TicketView(nextcord.ui.View):
@nextcord.ui.select(
placeholder="Reason For Ticket",
options=[
nextcord.SelectOption(label= "Enquires", value ="enqiries"),
nextcord.SelectOption(label= "Donation", value ="donation"),
nextcord.SelectOption(label= "Ban Appeal", value ="ban")
]
)
async def set_ticket(self, interaction: nextcord.Interaction, select_item: nextcord.ui.Select):
ticket = f"{interaction.user.name}-{interaction.user.discriminator}-ticket"
everyone = nextcord.utils.get(interaction.guild.roles, id=1104921291770826833)
overwrites = {
everyone: nextcord.PermissionOverwrite(read_messages = False),
interaction.user: nextcord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: nextcord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
ban_app = interaction.guild.get_channel(os.environ['BAN_APPEAL_CATEROGY_ID'])
enquiries = interaction.guild.get_channel(os.environ['ENQIRUIES_CATEROGY_ID'])
donation = interaction.guild.get_channel(os.environ['DONATION_CATEGORY_ID'])
member_role = interaction.guild.get_role(1108523138834239615)
@rustic onyx client does not support prefix commands, bot does
that's why bot is in the commands package
tysm for the answer
is there a way I can show an app command only to users with certain roles?
don't think so
you can do permissions but not roles i think
Hello, how can i check for manage_messages permissions in purge command
import discord
from discord import app_commands
from discord.ext import commands
HELLSING_GUILD_ID = 782077840908222516
class mod(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@app_commands.command(name='purge', description="Eliminar mensajes")
async def _purge(self, interaction:discord.Interaction, amount:int, member:discord.Member = None):
if amount:
await interaction.response.defer(ephemeral=True)
await interaction.channel.purge(limit=amount, bulk=True)
await interaction.followup.send(f'Se eliminaron {amount} mensajes.')
async def setup(bot):
await bot.add_cog(mod(bot))
@app_commands.checks.has_permissions(manage_messages=True)
also what is _last_member
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
ty
just ask your question
anyone know how can i always run main file no matter what file i am on? i am using code runner extention on VS code
is it just me or is registering slash commands taking long?
If you're syncing globally, then probably
really? i thought global registering times were shortened a few months ago
Should only take a few seconds
Why tho- also don't use code runner, it's just not well made for python
@bot.slash_command()
async def pgdb(inter: ApplicationCommandInteraction) -> None:
"""Ping the database."""
if db is None:
await inter.response.send_message(
"❌ No connection has been made", ephemeral=True
)
return
if db.is_closed():
await inter.response.send_message("❌ Database is closed", ephemeral=True)
return
await inter.response.send_message("✅ Database is fine", ephemeral=True)
async def main() -> None:
"""Starts the bot."""
load_dotenv()
await connect_to_database()
await initialize_database()
await bot.start(os.environ["BOT_TOKEN"])
if __name__ == "__main__":
asyncio.run(main())
``` could there be something wrong?
the cmd is just not showing up in the server
I don't use pycord or whatever this is
ah nah this is disnake
ok
well i got used to it cuz it auto saves code but now i am not using it, i am running manually by prompt
well, regardless of library, are there any common causes for the commands to not show up?
Just use the python extensions run button? Autosave is also built into vsc
uhh not syncing
with python extension is it possible to run a specific file no matter the selected file
Why would you want to do that
i sorted bot in different files, when debugging have to run main file again and again to see but i am on one the other files changing things and hoping it to work. in short i have to shift to main file again and again to check my code
i am trying this to transform a list of .Role and .TextChannel objects into a list of their ids but its not wrking, i dont get it.
Just
channels = [...] # your list of channels
channel_ids = [channel.id for channel in channels]
How hard can it be
Why do you want a list of their IDs anyway? You can just access them by the property
well some of them can be a string too
i am gonna use ids for uh, storing? in database? like a welcome channel and stuff
What??
the list, it has channels, roles and strings. thats why i wanted strings to stay same but channels and roles gets replaced by the ids
Then just
data = [...] # your list of channels, ...
ids = [channel.id if hasattr(channel, "id") else item for item in data]
How hard can it be
ok I have a problem and I've been sent here to ask
I need to iterate a function separately for each server my bot is in, so I put it in a class
but I can't dynamically instantiate the class
I have the guild ids via
var = []
for guild in client.guilds:
var.append(guild.id)
!list-comp 
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
What's that even mean
basically I have a settings function that's specific to one server. I've put it inside a class so it can iterate separately and have different settings for different servers
but in order to instantiate the class I need to set the name which I can't do dynamically
like, I can do
12345 = Test()
but not
guild.id = 12345
(guild.id) = Test()
obv that's not valid syntax but that's the goal
What goal
to create an object dynamically, using the id as a part of the name, which is an instance of the class Test()
Why? just why
Then just store them somewhere, like dict
so, in the function I define variables, and I want to be able to have a set of those variables for each server
which is what classes are for, right?
Show the code, I don't understand
okok
so I have a txt file for each server with their settings. The for line section reads the doc and stores the values of the settings
the if ic section makes any changes if the person running the function updated a setting
the final section updates the python variables
the idea is to have each server use its own instance of this function so I can run servera.var1 = x and serverb.var1= y
99% of it works, I just need to define the name of the object so it's unique but I can identify it
Where did you get this idea
Just use dictionary at this point, you'd get less trouble
the deepest depths of my brain I think 😭
I guess the question is, am I able to instantiate a class like that using a dict?
Why would you
why what 😐
What problem would be solved by being able to do it that way?
damn thanks. i didnt know about hasattr
it makes the entire settings function server-specific, so different servers can set and update a different set of settings.
It works when I hardcode the name of the object, but that doesn't scale well. If I can create the object name using the guild.id string/int, it's fully dynamic
it solves me having to manually write in "server23456 = Settings()" somewhere in the startup
every time another server invites the bot
Persistent, structured storage that the bot can query and write information to in a way sensible to your goal.
ok I'm sorry I know I'm being really confusing, let me boil it down.
I have a class and need to make an object ObjectNameHaha = Settings()
Is it possible to create the object by setting the name of the object from a variable
ObjectNameHaha = 12345
I would ask what the common implementation patterns are for bots.
How people organise things to deal with different settings per server.
Well for large servers they use sharding which I think is different instances of the bot altogether, but that's "not recommended for bots with less than 1000 servers"
Variables should always be static.
Nor should objects' behaviour alter based on what variables point to them.
If you want any sort of dynamic behaviour based on name, dictionaries are the go.
well the behavior of the class doesn't change based on what object is running, it's just that each object needs a separate set of the same variables while still running the function
Names being given to the instances at creation.
yes ^
that's what I need
I just need to give it a name at creation, where I have the name already as the value of a variable
class Bot:
def __init__(self, id_):
self.id_ = id_
bots = {}
id_ = 123
bots[id_] = Bot(id_)```Adapt as required.
d is unresolved?
Create beforehand. Sorry. It was implied.
dict
ok 1s lemme test this rq
it works
omg
looking back I realize this is what you had tried offering as a solution before, but I had asked if you're able to define the class object in a dict and the conversation had moved on 😐
I appreciate you all, sorry for being such a headache lol
All good.
now I just have to figure out how to update the rest of the bot to use the server-specific vars
wish me luck 😭
why not a database
you said something that scales well
idk a thing about databases
what you're saying doesn't make sense at all, you're not saving the server settings anywhere
that doesn't scale well either
Is that a problem?
After all, not knowing something is one of the easiest problems you can fix.
very true but solving a problem by using the knowledge you have does work sometimes 😐
except when I'm a stupid little baby
at some point you are going to find that text files do not fit your use case well enough
databases are meant for storing data persistently and will work well per server since you only have to make a query
yes I will, as it scales the text files will be bad
it was my solution when the bot was just in one server, and while it works for a small sample relatively well, it will eventually become highly inefficient. But I'll cross that bridge later because it's a working solution for now that lets me work on scaling other aspects of the bot
good to know, I'll keep this in mind for sure
why not at least use json so you don't have to parse the text files
that is a good idea actually, I understand that json is good for that sort of thing. I'll look into that
Hello, I'm trying to make a slash command only work in DMs but this doesn't seem to be working
@bot.tree.command(name="report", description="Report a user to our team!")
async def report(interaction : discord.Interaction):
print(interaction.channel)
if not isinstance(interaction.channel, discord.DMChannel):
await interaction.response.send_message("Please use this command in DMs!", ephemeral=True)
return
It returns False even in DMs
how can error handle in slash commands?
If you want one general one for all slash commands, something like this
@bot.event
async def on_slash_command_error(interaction : discord.Interaction, error):
if isinstance(error, commands.CheckFailure):
await interaction.response.send_message("You don't have permission to use this command!", ephemeral=True)
elif isinstance(error, commands.CommandNotFound):
await interaction.response.send_message("Command not found.", ephemeral=True)
else:
print(f"An error occurred: {error}")
thanks
TIL that slash commands work in DMs apparently.
i was about to say, "they don't work in DMs", but apparently they do.
that does not work
Ah I wonder why, it works for me
any associated error?
does CheckFailure = Missingpermissions
MissingPermissions
does that come in the terminal or?
yes
oh
should i change CheckFailure to Missingpermissions @swift acorn?
Oh yeah sorry, because in my code I have a custom check on commands
ok
oh
why does it still not work
its still showing the error in the consle
*console
just check interaction.guild instead
this event does not exist
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
yeah I was just trying it out and I noticed I just saw it from somewhere and implemented it never tried it
I am just checking with interaction.id and channel.id now it works
why would you do that
because it works
there's a much easier way
if interaction.guild is None:
await interaction.response.send_message("This command can't be used in DMs.")
return
ah but I want it to be used in DMs only
alright thank you I will do that then
also may I ask how I can handle slash command errors then
so
@CommandTree.error
# do stuff here?
sorry I like can never understand it from docs until I see an example
i tried it didnt work as expected now im using other stuff sorta working
class PreviewButton(ui.Button):
async def callback(self, interaction: discord.Interaction):
response = requests.get(preview)
with open(f"{name}.mp3", "wb") as f:
f.write(response.content)
with open(f"{name}.mp3", "rb") as f:
await interaction.response.send_message("Here's the preview:", file=File(f, filename=f"{name}.mp3"))
I am trying to make the bot sends an mp3 file when a button is pressed, but I don't know if this is the correct way
What's wrong with it? If it works, it works
sigh requests
Not efficiently though
'File' is not defined
I wonder why
I really dont know why 💀
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
i think i have closed it
making a request with the requests module will block the event loop of the bot (this mean that your Bot will not be able to respond to commands and other things)
you should use an asynchronous module to make requests such as aiohttp
!pypi aiohttp
Show the full code, you could have missed it somewhere else
and you don't need to save the file to send it, you can just use io.BytesIO
with the aiohttp package?
Traceback (most recent call last): File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call await command._invoke_with_namespace(interaction, namespace) File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'snake_ladders' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction [2023-05-21 13:45:44] [ERROR ] discord.ui.view: Ignoring exception in view <Dices timeout=20 children=2> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Roll!' emoji=None row=None> Traceback (most recent call last): File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task await item.callback(interaction) File "e:\spikey\spikey.py", line 744, in menu2 client.click[interaction.guild.id].set_result(True) asyncio.exceptions.InvalidStateError: invalid state
client.click[interaction.guild.id].set_result(True) is an asyncio.Future() object
!pypi asyncio
with aiohttp you read the response and its bytes, with the bytes you construct a BytesIO object, later you'll pass the BytesIO object to discord.File
I see, thank you.
probably you need to defer the interaction
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
i tried commenting the whole code still its like this
thoi checked too
couldnt find any
!e true
import asyncio
async def main():
loop = asyncio.get_running_loop()
fut = loop.create_future()
fut.set_result(True)
fut.set_result(True)
asyncio.run(main())
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 11, in <module>
003 | asyncio.run(main())
004 | File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
005 | return runner.run(main)
006 | ^^^^^^^^^^^^^^^^
007 | File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
008 | return self._loop.run_until_complete(task)
009 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
011 | return future.result()
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/epatarirah.txt?noredirect
Dont you need to use one .describe?
You've probably already set the result
there's a syntax error in moderator_logs
yeah i did use it
view = ui.View()
view.add_item(CanvasButton(label='View Spotify Canvas', custom_id='CanvasButton'))
view.add_item(PreviewButton(label='Preview', custom_id='PreviewButton'))
embed = discord.Embed(title=name, color=discord.Color(value=int(color_without_hash, 16)))
embed.add_field(name="Release Date", value=f"<t:{timestamp}:D> (<t:{timestamp}:R>)", inline=False)
embed.set_thumbnail(url=cover)
embed.set_author(name=f"{artists}")
embed.set_footer(text=uri)
if canvas_url.startswith('https'):
await message.channel.send(embed=embed, view=view)
else:
await message.channel.send(embed=embed)
Any ways to only show PreviewButton even if canvas_url does not start with https?
do I call ui.View twice?
What
How would i format a items info, if the item info data that is going to be formatted is in a database?
just add the items in some if conditions
like if it start with https add what you want, otherwise add something else
how do i make my discord bot 24/7
you need a paid host
like what
I personally use Cybrancee it's not the best but cheap enough
no you don't
Also could anyone please tell me how to use this because I cannot figure it out 
can you help me with it rq like in a vc
sorry I can't rn, but on YT freecodecamp.org has a good video explaining it simply
How come
why
Anyone see my help post pls
You can ik 2 ways
can you help me with it in a vc
their machines are underpowered, they make your source code public including any secrets that you might've forgotten to leave out, their built-in editor sucks, your server will shut down within a few minutes of inactivity, all to save a few dollars actually investing in a decent host
That's a website monitoring tool
It has nothing to do with hosting
And don't even try to use it with replit
paired with uptimerobot. I've used it and it works
^ uptimerobot just keeps pinging the webserver making replit think that the repl is actually active.
You'll be rate limited eventually
i dont really care if i have to pay for it or not im just trying to get it to work 😦
if you have a credit card you have decent options like azure, digitalocean, google cloud etc open for ( a year or so ) for free.... you can also use railway.app for free
use something like a systemd service or a docker container
sigh
the problem isnt that i dont know what service to use its more about when i try to get the bot running with the service the bot wont launch
you need to install python and your project requirements on these services
which might include but is not limited to discord.py
is there anyone who can help me in a vc with it
wait railway is free?
for 20 days~/month , if you provide credit card info it can last for even 30 days/month
i dont know how to get the bot to launch in a cloud but i can launch it from the file
are you making a systemd service
what does that mean
systemd is a service manager for linux
well i dont think im doing anything like that
you should it's better than just running the bot
can you help me in a vc pls
no
is it like dockerizing the Bot?
why does no-one want to help me for something that would take someone who has done this before like 5 seconds
nobody wants to join vc
including me
i cant even talk in the vc i think i still have like 2 days and 30 more messages
yes i will dockerize leaf eventually
cool
mhm start with the bot, later you'll think how to host and deploy it
how to make transcript file in ticket system ?
..why?
though leaf is still not dockerized 
to get it out there
Getting an unfinished and incomplete product out there is useless
no it's not
How do you explain Leaf having a total of 5 users then
because it's not deployed
the bot works perfectly fine its just i dont want to have to turn my computer on whenever someone wants to use it
hk only has about 30 though so it's ok
Ah I see you are at the "Do as I say, not as I do" stage
yes
My bot does not output any errors, it just does nothing when attempting to make it connect to vc. Is this not the correct code for making it join vcs?
how to make transcript file in ticket system ?
my code is:
async def transcript(self, interaction: discord.Interaction, button: discord.ui.button):
if isinstance(interaction.channel, discord.TextChannel) and interaction.channel.category.id == 1109771830685880370:
transcript = ''
async for message in interaction.channel.history(limit=None):
transcript += f'{message.author.name}: {message.content}\n'
with open(f'transcript-{interaction.channel.name}.txt', 'w') as file:
file.write(transcript)
await interaction.channel.send(file=discord.File(f'transcript-{interaction.channel.name}.txt'))
your command is probably not running
also you need to check if the user is in a voice channel, and replace ctx.message.author with ctx.author
I tried adding the print statement in the command printing the name of the voice channel I am in, but it printed that fine?
basically added print(c)
do you have the voice_states intent?
i tried adding that too
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
or am I missing that?
yes, because my bot used to do it fine before, after updating discord.py, something appears to have changed
Idk if im late but use .all instead of default
How to disable a button after it has been clicked once and on timeout
Set the button's disabled property to False and edit the message with the updated view
isn't that false by default?
context.bot.send_message(chat_id=update.effective_chat.id, text="Successfully!")
^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'bot' ---------- the telegram bot wont say "Succseffully in chat"
My bad, set it to True
can u give a simple example
Telegram? This is #discord-bots channel 🍨
theere is no help page for my problem
u can create a forum
class CusView(ui.View):
def __init__(self):
super().__init__(...)
self.message: discord.InteractionMessage | None = None
async def on_timeout(self):
if self.message is not None:
await self.message.edit(...)
async def a_command(inter: discord.Interaction): # Just imagine this as a slash command callback
view = CusView()
await interaction.response.send_message(..., view=view)
view.message = await interaction.original_response()
Just edit the on_timeout to disable your button. I'm too lazy to do it
How would you make a fancy reaction button where the bot sends out a message that says like click this below to receive your role
Thanks
you are not, and I followed your idea just now and did not work
!eval
Lista=[1,2,3]
Lista.delete(0)
Print(lista)
!eval
Lista=[1,2,3]
Lista.pop(0)
print(lista)
@whole shoal :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(lista)
004 | ^^^^^
005 | NameError: name 'lista' is not defined. Did you mean: 'Lista'?
#bot-commands
Alr
Will that effectively hide it or appear normally and just make it fail the check
Though it's most likely supported, since Discord allows it
Just don't hide it for role concerned and hide for the others?
!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.
when doing the / command, the application isn't responding.
Error code: iscord.app_commands.errors.CommandInvokeError: Command 'role_reaction' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'
Code:
async def role_reaction(ctx):
embed = discord.Embed(title="~ Become A Subscriber! ~", description="React to the :Galleon~1: to receive the @Subscriber role to stay notified on our future projects, changes, analysis, and news!", color=discord.Color.blue())
subscriber_emoji = '\N{SHIP}'
poll_emoji = '\N{MEMO}'
embed.add_field(name="~ Get Notified For Polls! ~", value=f"React to {poll_emoji} to receive pings whenever we have a poll in #poll", inline=False)
message = await ctx.send(embed=embed)
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)```
Interactions don't have a context but an interaction as parameter
Use interaction.response.send_message instead
where?
So you'll first need to replace ctx with interaction or inter or whatever
whats the bot attribute that lets you send a message?
And then use that instead of ctx everywhere and replace the .send. call
not ctx.send
To where?
well I'll handle the rest (message and where to send it)
but interaction is a unsolved reference
i need to put interaction in the () at the top?
As said, replace it in your parameters
aight
thanks, does the message.add_reaction need to be changed?
How would the bot have a send method if it doesn't know where to send anything?
Pretty sure it has been removed, you can use bot.http... though
Does it use ctx?
re-read my message
no
Just like the bot can use the raw API endpoint to send a message
Getting the channel object first is just to facilitate developers
I guess you can just make it yourself
It should be available in bot.http
Well that's once you have a text channel, yes
It's not just using the bot object as you've asked 
I didnt ask that
Yes you did
At that point just get the channel with get_channel
I said I'll handle the rest 🙂
bot attribute
and then use send
wont discuss over this 😄
You asked something that just has an attribute on the bot object
Which is http in your case
Hey, I need help!
I want to convert my cmd/linux but which only runs in terminal to a discord bot
peace 🧘♂️
Getting a text channel object before, then just use bot.get_channel and then send
sorry, the bot doesn't add the button to the message:
error code: discord.app_commands.errors.CommandInvokeError: Command 'role_reaction' raised an exception: AttributeError: 'NoneType' object has no attribute 'add_reaction'
code:
async def role_reaction(interaction):
embed = discord.Embed(title="~ Become A Subscriber! ~", description="React to the :Galleon~1: to receive the @Subscriber role to stay notified on our future projects, changes, analysis, and news!", color=discord.Color.blue())
subscriber_emoji = '\N{SHIP}'
poll_emoji = '\N{MEMO}'
embed.add_field(name="~ Get Notified For Polls! ~", value=f"React to {poll_emoji} to receive pings whenever we have a poll in #poll", inline=False)
message = await interaction.response.send_message(embed=embed)
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)```
X,Y problem moment 
wdym
That's because send_message doesn't return anything
Not to you
how do you make it return?
@bot.tree.command(name="createrule")
@app_commands.check(has_perm)
async def createrule(interaction : discord.Interaction):
guild = interaction.guild
rule = await guild.create_automod_rule(
name="No spam",
trigger_type="message",
trigger_metadata={
"content": "(.*)spam(.*)"
},
actions=[
discord.AutoModAction.ban_user()
]
)
await interaction.response.send_message("Done!")
I am trying to create this automod rule but it says that ban_user is not a thing?
? Its just that the message.add_reaction doesn't add any reaction
why is this
how would you fix this
I might be wrong but I think it does?
No.
!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.
@lean harbor you need this to get the message
That will return your message, and then you can use it
oh yeah nvm that's the normal send that returns it
Would any of you happen to know anything about this?
would you just do:
await interaction()
It doesn't exist
Yeah got that, what do I do to make it ban the user then?
message = await interaction.original_response()
So wait for Discord to support it, or don't use AutoMod
alright, what's for timeout then?
timeout 
message = await interaction.response.send_message(embed=embed)
What bout this line then?
And since it's an attribute, there's no ()
gotcha thank you
And you need AutoModRuleAction objects with the type being discord.AutoModRuleActionType.timeout I guess
Then you can set the other attributes if needed
Or just pass the duration and the type will be automatically set
then how would it send the message
it doesn't need message = to send the message
Just with await interaction.response.send_message(embed=embed)?
Told you to remove specifically message =
Not the entire line
Do I pass it in actions like duration = 60
In the AutoModRuleAction object you create
https://discordpy.readthedocs.io/en/stable/api.html?highlight=send#discord.TextChannel.send is this the only method that lets you send messages ? 🤔
cause it doesnt seem to have a destination-related param
Can you... read?
though the description says: Sends a message to the destination with the content given.
Because the destination is the TextChannel object
@bot.tree.command()
async def role_reaction(interaction):
embed = discord.Embed(title="~ Become A Subscriber! ~", description="React to the :Galleon~1: to receive the @Subscriber role to stay notified on our future projects, changes, analysis, and news!", color=discord.Color.blue())
subscriber_emoji = '\N{SHIP}'
poll_emoji = '\N{MEMO}'
embed.add_field(name="~ Get Notified For Polls! ~", value=f"React to {poll_emoji} to receive pings whenever we have a poll in #poll", inline=False)
message = await interaction.original_response(embed=embed)
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)
like this
Why did you delete the entire line now
the one before?
I literally told you not to remove the entire line but to keep
await interaction.response.send_message(embed=embed)
message = await interaction.original_response(embed=embed)
await interaction.response.send_message(embed=embed)
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)
like this?
You probably want to send the message before getting the response
await interaction.response.send_message(embed=embed)
message = await interaction.original_response(embed=embed)
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)
As I told you countless times before, but since you seem to have issues reading, use the following:
await bot.http.send_message(channel_id, ...)
If you don't want to use that, then use the functions that are made for it - such as
channel = bot.get_channel(channel_id)
await channel.send(...)
tias
whats supposed to be in the parameter for message = await interaction.original_response()
nothing
aight
man chill out you seem to be really nervous
Nope, you just don't read :)
stop being aggressive I'm not interested in your help if you talk like this tbh
fyi you can see that in the docs
Take the time to read at least.. You haven't even bothered trying out bot.http yet expect to get help and come back over and over with your other functions and being sad about you not being able to specify the destination - which is solved with the functions I've mentioned multiple times above...
For this, How do i make it so the @ shows normally when you ping like a role
<@&ROLE_ID>
!d discord.Role.mention
property mention```
Returns a string that allows you to mention a role.
Seems like a static message, no need to get role objects for that
What
aight thanks
E.g.
await channel.send("<@&ROLE_ID>")
will mention a role in a basic message, now you can use the same in embeds, etc.
Hmm
@slate swan hey
@bot.tree.command(name="createrule")
@app_commands.check(has_perm)
async def createrule(interaction : discord.Interaction):
guild = interaction.guild
rule = await guild.create_automod_rule(
name="No spam",
event_type= discord.AutoModRuleEventType.message_send,
trigger = discord.AutoModRuleTriggerType.spam,
actions=[
discord.AutoModRuleActionType.block_message
]
)
await interaction.response.send_message("Done!")
It gives me the error
Command 'createrule' raised an exception: AttributeError: '_EnumValue_AutoModRuleTriggerType' object has no attribute 'type'
You need to pass objects
E.g. trigger requires a AutoModTrigger object
!d discord.AutoModTrigger
Krypton can you help me in a simple thing ;-;
class discord.AutoModTrigger(*, type=None, keyword_filter=None, presets=None, allow_list=None, mention_limit=None, regex_patterns=None)```
Represents a trigger for an auto moderation rule.
The following table illustrates relevant attributes for each [`AutoModRuleTriggerType`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoModRuleTriggerType "discord.AutoModRuleTriggerType")...
There you specify the type etc. and pass that to trigger=...
ah gotcha
Hmm ...
Same for the actions, they require a list of AutoModRuleAction objects
!d discord.AutoModRuleAction
class discord.AutoModRuleAction(*, channel_id=None, duration=None, custom_message=None)```
Represents an auto moderation’s rule action.
Note
Only one of `channel_id`, `duration`, or `custom_message` can be used.
New in version 2.0.
Bro can you tell me the syntax of on_message cmd
There you just pass the duration as parameter
And the type will be automatically set
understood tysm
Hmmm......
Don't use on_message for commands, use https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
mhm, how would you mention channels?
Replace @& with #
<#ID>
understood thanks
You're sending a command object as content
but it's a string
Nope
it's a variable, Oh wait
description=general_information
ye thats the name of the variable
Same name as your function name
yep thanks
Not really a good idea
ye i changed it
Sorry for the ping, But any idea how i can make the bot give a specific role if the user reacts to the message that the bot sent?
How can you respond to a slash command? With the goal of getting rid of:
Whats the error
I read you can respond by doing ctx.respond but that doesnt seem to be a valid function
no errors in my IDE
I think you need to do interaction, can u send your code?
@commands.has_any_role(".")
@commands.hybrid_command(
name = "embed",
description = "Send an embedded message to a desired channel"
)
async def send_embed(self, ctx: commands.Context, channel: str, set_author: bool, title: str, message: str):
embed = discord.Embed(
title = title,
description = message,
timestamp = datetime.utcnow()
)
embed.set_footer(
icon_url = config["AlgoRyze"]["Media"]["Logo"],
text = config["Discord"]["Embed"]["Footer"]["Text"]
)
if set_author:
print(ctx.author.nick, ctx.author.name)
embed.set_author(
name = ctx.author.nick if ctx.author.nick != None else ctx.author.name,
icon_url = ctx.author.avatar
)
# Replace <#> from the channel
if "<#" in channel:
channel_id = channel.replace("<#", "")
channel_id = int(channel_id.replace(">", ""))
channel = self.bot.get_channel(channel_id)
await channel.send(
embed = embed
)
I've had the same problem before where i have used ctx and it hasn't worked. If i'm not mistaken you need to do interaction. Don't quote me though i'm a beginner
@smoky sinew you free to help?
!d discord.ext.commands.Context.send - properly respond to it
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
nothing to do with the ctx?
What
it's fine
any idea how to make the bot give a person a specific role after they have reacted to a message the bot sent?
Code so far:
@commands.has_any_role("Executive")
async def role_reaction(interaction):
subscriber_emoji = '\N{SHIP}'
poll_emoji = '\N{MEMO}'
embed = discord.Embed(title="~ Become A Subscriber! ~", description=f"React to {subscriber_emoji} to receive the <@&1100505557389037689> role to stay notified on our future projects, changes, analysis, and news!", color=discord.Color.blue())
embed.add_field(name="~ Get Notified For Polls! ~", value=f"React to {poll_emoji} to receive pings whenever we have a poll in #poll", inline=False)
await interaction.response.send_message(embed=embed)
message = await interaction.original_response()
await message.add_reaction(subscriber_emoji)
await message.add_reaction(poll_emoji)```
!d discord.Client.wait_for - wait for the reaction
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
thanks
worked, thanks
dont apologize
why cant I go to the next line when passing a value for an argument. I'll send a screenshot
I want to have the message in separate lines
Welcome to slash commands, you can use \n though
You can also use modals
how could i get the channel a command was used in?
do you have context or interaction?
interaction
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
ah thought that wouldnt work, thanks for the recommendation 🙂
you could use a modal
🤔
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
\n wont work, will be part of the message :/
can anyone give me an example of a slash command called kick and that has as argument member: app_commands.Choice[str] i.e. has as choices the members of the chat in here it is going to be executed? (discord.py)
Can anyone see mine help post ;-;
We don't code for you, we help you solve issues with your code
It will be same as a normal command where u use member:discord.member
This will make the members show up as choices
Btw guys a question i have created a button for some reason whenever i click it it says interaction failed but the interaction is also being carried out like it gives a response like it's supposed to
Any idea on what might be the cause??
Typehint member as discord.Member
defer the interaction
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Yeah that fixed it
await interaction.response.defer()
await asyncio.sleep(5) # Doing stuff
await interaction.followup.send(f"deleted {amount} messages")
``` would this work?
Just try it
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.channel.purge(limit=amount)
#await interaction.channel.send(f"{interaction.user.mention} used the clear command to deleted {amount} messages")
await interaction.response.defer()
await asyncio.sleep(5) # Doing stuff
await interaction.followup.send(f"deleted {amount} messages")
``` here is full command?
i did and i got this error ```Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "main.py", line 61, in clear
await interaction.response.defer()
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/interactions.py", line 638, in defer
await adapter.create_interaction_response(
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/webhook/async.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
You're supposed to call defer before doing anything that takes a long time to complete
oh ok
In this case, it's the purge
And you can just remove sleep, it's probably for an example someone gave
#bot-commands
defer
purge
followup thats the order generally
how to set a local file as an imbed image (embed.set_image) i tried using that discord.File thing but it sends the image outisde the embed and plus i cant even use it while editing embed
Can someone help me please. I am really not sure why I am getting this error here is my code:
class TicketView(nextcord.ui.View):
@nextcord.ui.select(
placeholder="Reason For Ticket",
options=[
nextcord.SelectOption(label= "Enquires", value ="enqiries"),
nextcord.SelectOption(label= "Donation", value ="donation"),
nextcord.SelectOption(label= "Ban Appeal", value ="ban")
]
)
async def set_ticket(self, interaction: nextcord.Interaction, select_item: nextcord.ui.Select):
ticket = f"{interaction.user.name}-{interaction.user.discriminator}-ticket"
Here is the error traceback:
Ignoring exception in view <TicketView timeout=180.0 children=1> for item <StringSelect placeholder='Reason For Ticket' min_values=1 max_values=1 options=[<SelectOption label='Enquires' value='enqiries' description=None emoji=None default=False>, <SelectOption label='Donation' value='donation' description=None emoji=None default=False>, <SelectOption label='Ban Appeal' value='ban' description=None emoji=None default=False>] disabled=False>:
Traceback (most recent call last):
File "C:\Users\calcu\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File ~~"C:\Users\calcu\Desktop\Python Development\Inner City RP\cogs\commands\set_tickets.py~~", line 52, in set_ticket
ticket = f"{interaction.user.name}-{interaction.user.discriminator}-ticket"
AttributeError: 'StringSelect' object has no attribute 'user'
Can someone help me add an thumbnail to my discord bots embed
I tried discord.Embed.set_thumbail(*, url)
do you mean an image like this:
You need to do ```py
embed.set_image(url="URL HERE")
For the thumbnail you can do this
embed.set_thumbnail(url="url")
Note: the thumbnail uri must be https
Do you know how to make your bot get an image like if someone does command ,av @the_-user it shows the user avatar or pfp
You will have to do something like
async def function(ctx, member: discord.Member):
await ctx.send(member.avatar.url)
I think anyway should be something similar
Oh ok
Sorry my mistake its member.avatar.url
Wasn't it member.display_avatar??
I'm using nextcord and it looks like its member.avatar.url
For discord.py it's member.display_avatar
^ My bad
member.avatar.url usually gives an error if the user has no pfp
Is anyone able to help me out?
probs be something like on_member_role idk
This works too
There might be other ways too but this was the first one that came to mind
U can also create an event where whenever a user gets a role the bot sends a message in a specified channel
U should try going through docs
U might find something there
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
why is my bot sending messages twice while in my code, it should be sent once
probably have 2 python instances
where
how do I kil
are you on windows?
then kill them from the task manager
send code
the whole source code?
this happens for each command
and I see that when I open vsc, a python is already running
Mash Allah your bot is good
thank you
but its not the bot that is issuing
its another (i sent ss above)
Sayous ^^
I see
do you have an on_message listener
yeah
are you calling process_commands in it
no
@bot.listen('on_message')
async def message(message):
await bot.process_commands(message)```
only this
but isnt thats listen thing
only do that if you use the event decorator since it replaces the bot object's internal event
because maybe you weren't using a listener before
btw your bot is in my server
Hello there, can I get help with this code. The problem is that my stuff is not updating to my database.
https://paste.pythondiscord.com/nodasiqema
jazakallahu khair
The bot works perfectly but I want to know why is it showing it on the terminal?
no thats logger and this log is of type INFO which means its just information not error nor warning
if you wish to not log out INFO logs you can specify that when starting bot
!d discord.ext.commands.Bot.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect").
d.py and forks doesn't handle logs for you so if you don't create a log handler (or set a Basic logger) you won't get logs
so why is he getting logs
doesnt d.py has logger built in?
afaik no, if you don't setup it
Can someone give me an example on how to make your discord bot make an member go afk like if the member says !afk or ,afk it makes the user go afk and the bot says in a embed that the user is currently afk and then once the member speaks it responds with user it now back from afk for however long the member was afk for?
why does the bot answer "Ja, Nein, Vielleicht, Oder?, Warum?, naja, okay" with random letters?
Hello, how i can hide "Santtiago used /say" in the cmd response
@app_commands.command(name='say')
@app_commands.checks.has_permissions(manage_messages=True)
async def _say(self, interaction:discord.Interaction, content:str):
await interaction.response.send_message(content)
So when i do this i do @client.event Async def av(ctx, member: discord.Member): await ctx.send(member.display_avatar)
Im kinda new to coding so i dont rlly know a lot of things about coding im sorry
member.display_avatar.url
and it's a command, not a @bot.event
Also d.py is not intended for newcomers but rather for people with experience, worth learning python and OOP beforehand
ty
how do i set persmissions to my bot?
i'm planning to use those permissions to my bot:
Bots can't use soundboards so you don't have a feature that uses it, no point on asking that permission.
Nonetheless once you've chosen the permissions your bot really needs to function, it will provide you a link at the bottom which you can copy paste and invite the bot with the permissions above.
i forgot how do i invite my bot using this
didn't got it:
it's not generating
bot, then this:
what is my bot id?
That should be disabled, just as side note
@client.tree.command(name="clear", description="clear messages (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.channel.purge(limit=amount)
await interaction.response.defer()
await interaction.followup.send(f"deleted {amount} messages")
``` this doesnt work properly
it does purge sometimes
and sometimes it fails
async def purge(self, interaction: nextcord.Interaction, number_of_messages: int):
if interaction.user.guild_permissions.manage_messages:
await interaction.channel.purge(limit=number_of_messages)
await interaction.response.send_message(f"Purged *{number_of_messages}* messages!")
else:
await interaction.response.send_message("You do not have permission to use this command.")
This is my purge command, maybe try this. It works you'll need to change nextcord accordingly
I'd recommend moving the await interaction.response.defer() line before the await interaction.channel.purge(limit=amount) line
Because the interaction fails if interaction.channel.purge takes over 3 seconds
You should generally defer the first thing you do, then do the computationally expensive task (the .purge() in this case)
This is how it should be:
- Defer immediately
- Do the thing that takes a long time
- Send follow up message
This is how you have it:
- Do the thing that takes a long time
- Defer
- Send follow up message
it doesnt purge anything
only if i put the amount = 1
so if i put anything number except 1 it doesnt purge anything
Im trying to delete original command message
@app_commands.command(name='testroles')
async def _avatar(self, interaction:discord.Interaction):
await interaction.message.delete()
view = DropdownView()
await interaction.channel.send('**🌎・ País**', view=view)
discord.app_commands.errors.CommandInvokeError: Command 'testroles' raised an exception: AttributeError: 'NoneType' object has no attribute 'delete'
so if i put anything number except 1 it doesnt purge anything
someone help?
I have once again returned to give everyone headaches with my complicated problems 🎉
So I've been working on a discord bot and it was working fine. I put a large portion of the code into a class so different servers can have different instances of everything(things like settings and functions and whatnot)
That's... odd
Seems like something you'd use a database for
relatable
when you init a superclass into a subclass, does it rerun the superclass's init or inherit the already init variables
Can anyone help me please:
async def set_ticket(self, interaction: nextcord.Interaction, select_item: nextcord.ui.Select):
member = interaction.user
AttributeError: 'StringSelect' object has no attribute 'user'
maybe switching the args helps
In discord.py it's self, interaction, select but nextcord seems to have changed it
ok so I might've realized what's going on but now that raises another problem
np
initially it was select, interaction iirc
like in buttons
when I'm running the superclass init in the subclass, it's resetting all of the variables because I'm rerunning init(which defines all of them as None). I already have an instance of the superclass in which the subclass is being created. Is it possible to reference that in the superclass init?
1s working on it lol
How can I hide this
you can't
oh rip
you can send a message to the channel instead of responding
yes I just thought of that
class Settings:
def __init__(self):
#defines all used variables as None
async def initchecks(self, setting, message, guild):
self.logcheck = Stopwatch()
class Stopwatch(Settings):
def __init__(self):
Settings.__init__(self)
#more variables
so all variables defined in Settings are being reset to None when I run Stopwatch because I'm using settings as a superclass
am I able to change the superclass to a particular instance of the superclass instead?
use super() when possible
instead of
someone can help?
So instead do
class Stopwatch:
def __init__(self):
super(Settings)
?
message = await interaction.original_response()
await message.delete()
super().__init__(pass params here if needed)
Why won't this work: ```py
channel_id = nextcord.utils.get(self.bot.get_all_channels, id=int(channel_id))
oops
!e forgot the self
class A:
def __init__(self, x):
self.x = x
class B(A):
def __init__(self, x, y):
super().__init__(x)
self.y = y
b = B(2, 3)
print(b.__dict__)
@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'x': 2, 'y': 3}
guild.get_channel
!d discord.Guild.fetch_channel if its not in cache
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread "discord.Guild.get_channel_or_thread") instead.
New in version 2.0.
ok I've definitely messed something up but idk what
let me show you what I've got going
How do I update an attachment in webhookMessage.edit?
hOw dO i UpdAte aN aTtaChmEnT iN wEbhOoKMesSagE.eDit
☠️
class Settings:
def __init__(self):
self.freq = None
async def initchecks(self, setting, message, guild):
#section that reads text file into list and pulls values from file
#sets self.f = 10
if self.f is not None:
self.freq = (int(self.f)*60)
print(self.freq)
class Stopwatch(Settings):
def __init__(self):
super().__init__()
self.start_time = 0
self.stop_time = 0
self.now_time = 0
self.elapsed = 0
self.timeron = None
async def current(self):
self.timeron = True
while self.timeron:
self.now_time = time.time()
self.elapsed = int(self.now_time) - int(self.start_time)
if self.elapsed == freq:
break
NameError: name 'freq' is not defined
webhook.edit_message() exists
It's an embed
what have you tried?
message= await message.edit(embed=embed, view=view, and i need to attach the file here)
if self.elapsed == self.freq
there's an attachments kwarg
class Settings:
def __init__(self):
self.freq = None
async def initchecks(self, setting, message, guild):
#section that reads text file into list and pulls values from file
#sets self.f = 10
if self.f is not None:
self.freq = (int(self.f)*60)
print(self.freq)
class Stopwatch(Settings):
def __init__(self):
Settings.__init__(self)
self.start_time = 0
self.stop_time = 0
self.now_time = 0
self.elapsed = 0
self.timeron = None
async def current(self):
self.timeron = True
while self.timeron:
self.now_time = time.time()
self.elapsed = int(self.now_time) - int(self.start_time)
if self.elapsed == self.freq:
break
proof?
returns None
in what method?
anyways, you're not returning anything, so that's... normal
Just a minute
does someone know if theres a bot I can send a list of emojis and it gives me a link to download those?
below self.elapsed = int(self.now_time) - int(self.start_time)
I have print(self.freq)
which prints None
show me your actual code then
I can't see that in the code you've given
custom emojis?
async def current(self):
self.timeron = True
while self.timeron:
self.now_time = time.time()
self.elapsed = int(self.now_time) - int(self.start_time)
if self.elapsed == self.freq:
break
print(self.elapsed)
print(self.freq)
await asyncio.sleep(0.98)
continue
if self.timeron:
self.timeron = False
#awaits function
every second it prints
0
None
1
None
2
None
@potent spear
message=await message.edit(embed=embed, view=pick, attachments=file) File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 841, in edit return await self._state._webhook.edit_message( File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1959, in edit_message with handle_message_parameters( File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 231, in handle_message_parameters files = [a for a in attachments if isinstance(a, File)] TypeError: 'File' object is not iterable
where are you declaring self.freq in that class?
message says it all
It's declared in the superclass, Settings
you're most likely doing
attachments = a_file
instead of
attachments = [a_file]
yes
Hm
yeah, as None... so what did you expect?
initchecks doesn't change its value
I have print(self.freq) under if f is not none and it returns 600
it's just an issue with the subclass
https://top.gg/bot/750406366094557244
first thing I found, not idea if it works
proof?
what like a ss?
no, the proof where all the code comes together
where you actually call that method and the other one afterwards
in the same object
your Stopwatch init isn't completely correct
Settings.__init__(self)
should be super()
ty 🙂
thank google
Oh yeah it worked thank you man
gl hf
I since changed it to super().init() per your recommendations and it's giving None
class Settings:
def __init__(self):
self.freq = None
async def initchecks(self, setting, message, guild):
#skipping the first part
if self.f is not None:
self.freq = (int(self.f)*60)
# self.freq = 10
print(self.freq)
if self.r is not None:
self.remf = (int(self.r)*60)
# self.remf = 10
print(self.remf)
if self.b == "on":
self.checktimer = Stopwatch()
self.checktimer.start()
self.checkping = "clear"
self.setcheck = True
await self.checktimer.current()
elif self.b == "off":
self.checktimer = Stopwatch()
self.timeron = False
self.cleared = True
self.alert = False
self.setcheck = False
print("checks off")
elif self.b is not None:
print("Error, no value extracted")
print(self.setcheck)
class Stopwatch(Settings):
def __init__(self):
super().__init__()
self.start_time = 0
self.stop_time = 0
self.now_time = 0
self.elapsed = 0
self.timeron = None
async def current(self):
self.timeron = True
while self.timeron:
self.now_time = time.time()
self.elapsed = int(self.now_time) - int(self.start_time)
if self.elapsed == self.freq:
break
print(self.elapsed)
print(self.freq)
await asyncio.sleep(0.98)
continue
if self.timeron:
self.timeron = False
#runs function
in if self.b I define self.checktimer = Stopwatch()
don't define self.freq as None in your init if you're never using that value anyways...
in pycharm it raises a squiggly if I don't
removing self.freq from init and running returns
if self.elapsed == self.freq:
AttributeError: 'Stopwatch' object has no attribute 'freq'
which I think means that the superclass init was the only value of freq it had
that's because you're never running that method which defines your self.freq attribute FIRST
so despite self.checktimer = Stopwatch() being after self.freq = 10, I have to run it again?
I'm sorry I'm a little lost don't mind me 😐
would it be easier to show you in a vc where I can ss and show the full logs? That might help
I print a lot of debug info
no, this is great practice to keep your code as simple as possible
I see your issue
the Stopwatch object you're creating right?
is completely separate from the settings class it's in
😑
they don't share the same variable values
what do you mean exactly by "download emojis"
I think it just converts them to png or whatever
that's easy
so how can I translate the value of self.freq in settings to a value in stopwatch
What's the event to detect if a member gets mentioned?
in on_message, you can check this
Ah alr
if a_certain_member in message.mentions :
Yeah i got it.. it will just be a pain sadly
can you comment in your code where the issue is happening? I've lost it for a while
class Stopwatch(Settings):
def __init__(self):
super().__init__()
self.start_time = 0
self.stop_time = 0
self.now_time = 0
self.elapsed = 0
self.timeron = None
async def current(self):
self.timeron = True
while self.timeron:
self.now_time = time.time()
self.elapsed = int(self.now_time) - int(self.start_time)
if self.elapsed == self.freq:
break
print(self.elapsed)
print(self.freq)
# IS RETURNING NONE
await asyncio.sleep(0.98)
continue
if self.timeron:
self.timeron = False
#runs function
lol like that?
class Settings:
def __init__(self):
self.freq = None
async def initchecks(self, setting, message, guild):
#skipping the first part
if self.f is not None:
self.freq = (int(self.f)*60)
# SHOULD BE SETTING "self.freq = 10"
print(self.freq)
if self.r is not None:
self.remf = (int(self.r)*60)
# self.remf = 10
print(self.remf)
if self.b == "on":
self.checktimer = Stopwatch()
self.checktimer.start()
self.checkping = "clear"
self.setcheck = True
await self.checktimer.current()
elif self.b == "off":
self.checktimer = Stopwatch()
self.timeron = False
self.cleared = True
self.alert = False
self.setcheck = False
print("checks off")
elif self.b is not None:
print("Error, no value extracted")
print(self.setcheck)
I'm going to grab some p rolls, I'll be back in a sec
you still have to show me how you create an object out of this class and call its methods, then we're all set
I have no idea in which order you're calling these methods based on some classes and their methods
So I had issues with this last night, I think the solution was putting it in a dict
let me grab it rq
global d
d = {}
for guild in client.guilds:
d[guild.id] = Settings()
await d[guild.id].initchecks("initall", None, guild.id)
What I actually expect and hope to see from you:
settings_obj = Settings()
settings_obj.initchecks()```
close enough...
so in the dict I have a separate instance of Settings() for each guild id given
why is your Stopwatch a subclass of your Settings in the first place? it doesn't seem like it has much to do with it anyways, right?
that certain settings needs a stopwatch, ok, I get that
but a stopwatch isn't necessarily a setting, right?
I've turned Settings() into more than just settings, I have basically all functions included that I want to be sharded by server
so each server has its own iteration of the function
what...
that's uhm, still irrelevant to my question
why is your stopwatch a setting? why can't it be something completely separate?
I mean it's not a "setting", it's just in the "Settings" class
it IS a setting tho, as Setting is its superclass :/
the settings class has a lot more than just the settings function like it originally had when I made it
idk man my brain is mush rn
seems like your Stopwatch just needs to be separated from your Settings class
it just keeps track of when it was created etc, I get that, but that's it
it's more like a dataclass imo
ok 1s I'm just adding an arg to pass the guild id so I can call the var externally
ok it works lol
idk why but I thought it would be easier and more convenient to just get the value from being in the class itself
I don't think so, as the admin has the highest perms
my solution for those issues: my bot is my guild admin 🙂
try to be as independent as possible when creating classes etc
you could create a class inside a class (without inheritance) if it's not relevant outside of it
but that's just A way, not THE way
Well that's not really nice....
I managed to finish the afk command tho... this is the last thing i gotta do
How can i add a timestamp?
That would look even nicer honestly
in...? an embed?
Nope lol
it's a util
for example spooky went away - why - how long ago
<t:1684708012:f>
you can get a datetime object of that, right?
Got it
Hi everyone how are you today ?
<t:1684708050:R>
https://discordpy.readthedocs.io/en/stable/api.html#discord.utils.format_dt
the style you want is "R"
You can help me for create a response visible only for people have write the command ?
the dt is just the dt of when he went away
it's called an "ephemeral message"
Yes
you can look in the docs on how to send messages where the ephemeral parameter is set to True in the send() method
Ok thanks
Is it optional?
Or what do i have to complete it with?
you've seen the link in the docs, right?
this formats the datetime object correctly FOR you, you could do it manually, but why when you have a util for it
await discord.Attachment.ephemeral.send(f"Your ticket is <#{ticket_channel.id}>")```
Its good or not ?
I don't understand how to use
format_dt(dt=<datetime_your_user_went_away>, style="R")
you have to learn how to read the docs first of all, as you're guessing
have you ever sent a message through a bot?
Yes just is my first time i try to use ephemeral
That's what i don't understand what do i fill dt with? i understood the rest lol
show me a testcommand where you make the bot send something
aight, gl
@bot.tree.command(name="kick", description="Kick member from guild")
async def kick(interaction, member : discord.Member, *, reason : str):
if (not interaction.user.guild_permissions.kick_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
if (interaction.user == member):
await interaction.followup.send(f"{member.mention} you can't kick yourself!")
return
await member.send(f"You have been kicked by {interaction.user} from {interaction.guild.name}.\nReason : {reason}")
await member.kick (reason = reason)
await interaction.response.send_message(f"{member.mention} has been kicked from the guild")```
did you write this YOURSELF?
Yes
alright, so you know what a method , and a parameter is, right?
Yes
the send_message method has a ephemeral attribute, if you set that to True, you'll send an only-readable-for-that-person message
send_message is a method you've used before as shown above
example
await interaction.response.send_message("I shat my pants, but don't tell anyone", ephemeral = True)
good, hf
Thanks bro
is there a timeout function in discord.py( or pycord) ?
discord.Member.timeout
thanks!
Quick question
Here i am checking if the command author is not the guild owner so it won't try to change the guild owner nickname because it's not possible
use != instead
Worked.
Yeah i understood now
Also when i uhh
When the member sends a message, afk will be removed.. And it should send a message of Welcome back {user}, You been away for {how long}
How can i tell for how long it been away? What's the best way to do so?
Store it in either a db or a bot variable in a dict
Key would be the user id, value the tile he went away
db if you want it to persist ( when bot reboots )
Aight, you can add the timestamp of when he went away I guess
That's the plan x)
that will be a string
Isn’t there a datetime datatype?
yes
i don't know.. That's why im here
store the utc-aware datetime preferably and then check that against the current datetime
let me make another field for datetime
Depending on the db you’re using, check its docs
I am using postgreSQL
but if the datetime returns a string i can just make a str field
But it would be easier to store the datetime datatype, true
Correct
You want the DB to do the conversion, not you
That’s good
It’ll have a datetime datatype probably
How to create a button ? I don't found in api
This is what i was able to find
!d discord.ui.View extend this
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
Example in code of the use of a button
thx
That’s great, you don’t even seem to have to pass a value when you leave it empty ( if you set auto now)
Well yeah it's a bool
But that's a class... not a field....
Seems like auto_now_set is your way to go. Then all that’s left is to reset it when he goes back online
Look for examples, you’re not the first one using datetime objects in tortoise for sure
why would you want it set to False
If i set it to True would it automatically get the current time?
yes
Oh
And what is that ?
modal
Ok thx
So if the timestamp is being added to the database, How can i pull it out?
like you do with all your other columns