#discord-bots
1 messages · Page 381 of 1
from discord.ext import commands
import sqlite3
import cogs.input
conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
await bot.load_extension('cogs.shift')
await bot.load_extension('jishaku')
await bot.load_extension('cogs.fun')
await bot.load_extension('cogs.utility')
await bot.load_extension('cogs.moderation')
await bot.load_extension('cogs.input')
print('Cogs loaded successfully')
except Exception as e:
print(f'Failed to load cog: {e}')
print(cogs.input.__file__)
print(cogs.input.setup)
bot.run('Cant have my token (:')```
Its small
There's a few things that are major issues here. But no idea why it would think that module lives in bot.py
wait, that's not you actually printing the module file -_-
please put the debugging prints at the top of your file before you do anything else
I put It at the top unter the imports and i get the same thing
Show your code, and show what you're getting
you should be printing the __file__ first
from discord.ext import commands
import sqlite3
import cogs.input
print(cogs.input.__file__)
print(cogs.input.setup)
conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
await bot.load_extension('cogs.shift')
await bot.load_extension('jishaku')
await bot.load_extension('cogs.fun')
await bot.load_extension('cogs.utility')
await bot.load_extension('cogs.moderation')
await bot.load_extension('cogs.input')
print('Cogs loaded successfully')
except Exception as e:
print(f'Failed to load cog: {e}')
bot.run('Token')
output:
c:\Users\willi\Desktop\Free_Novem_discord_bot\cogs\input.py
Traceback (most recent call last):
File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 7, in <module>
print(cogs.input.setup)
^^^^^^^^^^^^^^^^
AttributeError: module 'cogs.input' has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot> ```
And if you go to that directory and file, does it have a setup method?
No the file Is 100% empty in the folder but not iN VScode
I put the code In It
Did you...not save the file
That'll definitely do it lol
You wish
Still get It
Has no setup function but It does
Error doesn't lie
not with that attitude
Well f*ck me cuz Im staring at it..
using slash commands also need a bot like bot = discord.ext.commands.Bot(command_prefix=".", intents=intents)?
i mean am not using command_prefix or prefix commands
but still to make a Bot i need to give it
Yeah
not necessarily, no
you need a CommandTree more than that
i make it by bot.tree.command decorator?
btw is this ok i am learning buttons i think i made a heads tails ```py
class HeadnTail(discord.ui.View):
def init(self):
super().init(timeout=None)
self.heads = True if random.choice(["heads","tails"]) == "heads" else False
@discord.ui.button(label="Heads",style=discord.ButtonStyle.red)
async def heads(self, interaction: Interaction, button: discord.Button):
if self.heads:
await interaction.response.send_message("Its head")
else:
await interaction.response.send_message("It was tails")
@discord.ui.button(label="Tails",style=discord.ButtonStyle.blurple)
async def tails(self, interaction: Interaction, button: discord.Button):
if not self.heads:
await interaction.response.send_message("Its tails")
else:
await interaction.response.send_message("It was heads")
@bot.tree.command(name="toss")
async def toss(interaction: Interaction):
await interaction.response.send_message(content="Choose heads or tails",view=HeadnTail())
Client supports app commands, you don't need ext.commands at all. You just would make your own CommandTree if you were using Client
What's the output of py -m pip freeze?
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1721391182:f> (10 minutes) (reason: newlines spam - sent 112 newlines).
The <@&831776746206265384> have been alerted for review.
damn
!unmute @slate swan
:incoming_envelope: :ok_hand: pardoned infraction timeout for @slate swan.
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
oh aigh
Yeah you've got a load of competing libraries
how do ifix that
You should pick one discord library you want to work with, uninstall the rest, then reinstall that one
it's up to you which one you pick
how do i do that
Which part
you pip uninstall <lib> to uninstall a library
i wold have to do it to alot of my libs
add commas
oh aigh
but first decide which one u want to use
(preferably anything you do with python goes through py, i.e. py -m pip uninstall ...)
wdym
^^
whats the discord librarys i have
Ideally you should use discord.py
anything in that list which says discord
ok
so uninstall everything but discord.py
and then reinstall it with a 2.0+ version
how do i reinstall with a specific version
Could just uninstall, then install it again
while installing the lib, specify the version with ==<version>. Or if u want the latest version you could do py -m pip install -U discord.py
ok
(probably also using --force-reinstall)
pip install discord.py--force-reinstall ?
no, --force-reinstall is a parameter you'd put separately in addition to the above
Or, just uninstall discord.py and reinstall it
py -m pip install -U discord.py --force-reinstall
just uninstalled all and reinstalled discord.py
Then you can't use the other libraries you were trying to use
you need to pick one library, and have your code use it
You got yourself into a state where you were picking from different libraries that are incompatible with each other. discord.py almost definitely supports whatever you're trying to do, but you have to use its syntax if you want to pick that one
if i send u my code can u change it do fit discord.py?
I will not be modifying your code for you, no
ok
The changes should be fairly straightforward, but I haven't worked with all of these offshoot libraries to know how much they've diverged
i fixed it, js had topy -m pip install discord_webhook
You should not be installing multiple discord libraries
This causes unforeseen instabilities in the future
hello guys, this is not an advertisment but i wanna make friends with someone who knows python for discord bots to help me develop my own bot. the idea of the bot is complicated but if everything goes alright there is a chance to make money, even lots of money. dm who is interested in this and also i have no one to speak with((((
!rule tos
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Boost bots are against Discord's ToS, and can easily get your bot and yourself banned
Read the message of @unkempt canyon above, you won't get help to violate the ToS of Discord
ik
Your screenshot literally says boost bot
lmfao 😭
didnt know they were bannable bro
so many ppl habve them
what does a boost bot even do......
boosts a server alot of times in a couple seconds i think
Well, now you know. Also chill with the language, don't be rude to someone telling you about the rules
Sorry
How do I make a slash command resister faster?
how you all have active developer badge
big brain
hm?!
What makes you think they aren't registered?
what does resister mean
When I do / I cant see them -_-
I've re-ran the code loads
not your code, your client
Fixed and one more thing
from cogs import cogs.input```
Cogs Is the folder and cogs.input is the name of the file as input is Python I put cogs.input as the filename
What's the question?
I get a error. Well not a error It says the . is incorrect
That's not how imports work
Also if you're loading this as an extension, you don't also need to import
I have a file for log channel and when I need to send smth to It In another file idk how It would connect to It. As I dont have a on ready iN the other files

XD
I need shit from one file to be able to be used In another file
Like an extension?
I think I fixed It and got it working
https://paste.pythondiscord.com/SNCQ
Basically how the command is supposed to work is you run the command and insert all the stats, the stats transfer to a google sheetwith everything you put. Then if you run the command again and put a username that is already in the google sheet then it will update that persons stats and will add everything you put so for example if you had 5 touchdowns at first and then you do insert again with the same player and add 10 touchdowns then the player should have 15 touchdowns but heres the problem:
Every time I do /insert_qb_stats it works fine. But once I do it again with the same username meaning that it would update the stats, i have no clue why but all the data just messes up, like it passes on data to wrong stats or instead of adding on it just updates the number and idk why.
Are you trying to use a google sheet as a database?
no why
the database is cause i have other commands called /view_stats and /statleaders which shows stat leaders so basiccaly whenever I insert stats it makes a database for those commands but it goes straight to a google sheet that i defined at the top of my code
and im sure there might be an easier way of doing it but it works and its also not the problem the problem is the insertion from the command to the google sheet
There are better tools for tracking and storing data in your application. Namely databases
im sure but im not rlly worried abt that rn im js mainly trying to figure out the google sheet problem and then ill move onto finding better ways to store data application wise
so do u kno whats wrong w the google sheet or nah
Hey how can i do this:
async def confirmation_complete(self, channel):
for msg in self.confirmation_messages:
await msg.delete()
basically
it gives me error
await msg.delete()
^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'delete'
ofc but what can i do instead to delete confirmation_messages
send full code
yea nvm i js used follow up send and it detects msgs now
“Numpy is not avalible”
does anyone what this thing called?
I'm tyna search what this thing called, where it would display the add and remove
i already have the choice input just don't know how to add the display thingy where the user can see the two option of add and remove
I have a log_channel = {} but I need that to be used on more than 1 file. How would i do this?
As iN my bot.py I have a log channel command. And I need It to connect with other files so It can send message to that log channel.
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)```
I get this page cant be reached when I go to the link It gives me
Wait Flask can be used for Discord bots? Cool, I didn't know that
No Its a website for It lol
Like a dashboard
Oooh
hello guys i have a problem to start my finished bot if anyone is free to help me just dm me 😆
it's better to ask your question here as more people will see it
this question isn't suited for this channel, go to #web-development
you can type hint the arg as typing.Literal["add", "remove"] (making sure you got the import typing)
Anyone know how to make a dashboard?
do you know web development
class ConfirmButton(discord.ui.View):
def __init__(self):
self.joined = None
super().__init__()
@discord.ui.button(style=discord.ButtonStyle.green, label="Confirm", emoji="🆗")
async def confirm(self, interaction: Interaction, button: discord.ui.Button):
self.joined = True
await interaction.response.send_message(
ephemeral=True, content="Confirmed Your Place"
)
@discord.ui.button(style=discord.ButtonStyle.red, label="Cancel", emoji="❌")
async def cancel(self, interaction: Interaction, button: discord.ui.Button):
self.joined = False
await interaction.response.send_message(
ephemeral=True, content="Cancelled YOur place"
)
@bot.tree.command(name="comp",description="JOin a COmpi")
async def compi(interaction: Interaction):
await interaction.response.send_message("Welcome",view=ConfirmButton())
``` is this correct way of making button
now i want the buttons to disappear after user submits
You can respond instead with edit_message to edit the message the buttons are on. Passing view=None would remove the buttons
Yes
Guys can anyone suggest me some library's for create a good discord bot ? I want to create discord bot but I only heard about discord.py is there any better library's for that or ?
This is pretty subjective. What is it you believe about discord.py to be lacking?
m
@bot.tree.command(name='command')
Is this a correct way of creating slash commands?
My code is working without any errors but the bot is still not having slash commands
Did you sync them?
You need to sync them either through a command or on ready event.
You can do it in onready event like this:-
bot.tree.sync()
You really should not be using on_ready, especially not for things that are heavily rate limited like this
you shouldnt sync it in on_ready + its a coroutine method
I know. Still
That's alot of code to read ngl.
Also I need the function of your code too
There already exists a way of giving roles to people. You don't need a bot to do it, and if anything this is just reducing auditing and security
Why.
why are you using the on_message event instead of making it into a command
commands handle argument parsing for you
it doesnt have to do anything with replit
and dont use replit for discord bots whatsoever
use an actual code editor / ide for coding and buy a vps for hosting it
You can right click on members and add roles from that
bro i cant believe this, it just stopped working for no reason i will kms
my code:
and my error when i send user id or username of guy i want to deal with:
An error occurred: list index out of range
Add a condition in which you make sure that the list is not empty before you try to get the first item from it
why would list be empty tho, my input was user id or username
it worked like few hours ago
Can u show your traceback plz
It's okay i fixed it
Thanks for trying to help tho 
its the same as a normal emoji according to danny
what should i use to make slash commands and interaction UI in discord.py extend discord.Client with CommandTree or use discord.ext.command.Bot
commands.Bot if you plan to use cogs
Don't ask if there's an expert here. Just ask your question with all the details
depends. do you plan on ever having text commands?
if so, use bot
if you're 100% sure you're never going to add text commands you can simply use client with an attached command tree
sure
Can someone give me dashboard src?
We don't do that here, we help you code it for issues you face
What kind of question is that? Just try it and see
There's no partner thing anymore, so it's pretty simple
And vertification is currently stopped, since some years - so yeah
And common sense would tell you that you can't verify a server called "Discord" as it's the perfect scam
How do I change a roles color and icon? Couldn’t find it in the docs
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to do this.
All fields are optional.
Changed in version 1\.4: Can now pass `int` to `colour` keyword\-only parameter.
Changed in version 2\.0: Edits are no longer in\-place, the newly edited role is returned instead...
wasn't that hard to search imo
@bot.tree.command(name='buy')
async def buy(interaction: discord.Interaction, service_name: str, link: str):
services = load_services()
How do i make options for service_name instead of having to write the name
Is the set of options static or some kind of lookup?
static
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
Oh but i when i do this the slash command doesn't appear on discord anymore
Code? And how are you syncing them?
@bot.event
async def on_ready():
print(f'تم تسجيل الدخول باسم {bot.user}')
await bot.tree.sync()
print("Commands synced with Discord.")
bot.run('YOUR_BOT_TOKEN')
@app_commands.command(name='buy', description='Purchase a service.')
@app_commands.describe(service_name='The name of the service to buy', link='URL of the service')
@app_commands.choices(service_name=[
app_commands.Choice(name='hi', value='eeee'),
I have more options btw
What's the signature of the command method?
Also you should remove your syncing from on_ready asap or you're going to rapidly rate limit yourself out of developing
Oh
on_ready fires repeatedly and randomly, and is almost never the answer for something most people are trying to do
is it the correct way to sync my command anyways?
Why my slash command disappears when i make it with options but when i do it like that
@bot.tree.command(name='buy')
async def buy(interaction: discord.Interaction, service_name: str, link: str):
services = load_services()
It works
It is not
on_ready fires randomly and repeatedly. You do not want to sync randomly and repeatedly. Hence, it is not appropriate
@fast osprey
Should i give you my code
This code including the method signature
anybody know which is harder to code bots in? py or js?
Varies entirely person to person, it's very subjective
Someone who never touched js: js
Someone who never touched py: py
Someone who never touched js and py: Depends what they want to learn, if you learn you'll know it and then it won't be hard, doesn't matter the language
def EULAConfirmation():
os.system("cls")
print("Agree licence plz \n\n1. Accept\n2. Disagree\n3. Read license\n0. Exit")
while True:
try:
user_input = int(msvcrt.getch().decode())
break
except ValueError:
pass
if user_input == 1:
return run_bot_and_check_token_valid()
elif user_input == 2:
return "Bad opinion (Licence is magndatory to confirm)"
elif user_input == 3:
webbrowser.open("...", new=0)
return EULAConfirmation()
elif user_input == 0:
return 0
else:
return EULAConfirmation()
Is there a way to completely remove the ability to type not only characters but also other numbers besides 1, 2, 3, 0?
Wrong channel, something for #1035199133436354600
It's a channel for Discord bots, not basic Python stuff
Its actually for bot but ok thx
Your question has nothing to do with discord bots, it's basic Python stuff
It may be part of a discord bot project, but the queso is completely unrelated to discord bots
Wym
This is more of just a server-related question, but if I run a bot on a server via ssh, is it possible for me to quit this ssh session without stopping the process?
Use screen i guess
client = commands.Bot(command_prefix='!', intents=nextcord.Intents.all(), help_commad=None)
can i add the help_command = None so that I can customize my own help command?
Yes, look into screen or systemctl or tmux
Yes
You should pass in your own subclass instead
hi guys
i have such code inside my view class. add_buttons is a preparing function that is called inside __init__ and adds pagination buttons. and i also have close button created using @button decorator.
my problem is a close button position under message. i want it to be last one now its first. how can i do this?
https://media.discordapp.net/attachments/1256678894245777484/1264721806128971889/image.png?ex=669ee777&is=669d95f7&hm=aef96fc2f3442291ed83a43e00ac60ee25cb9c255c26590965903fc367a23212
def add_buttons(self):
self.add_item(PaginationButton(pagination_step=-5, custom_id='prev_pages', emoji=':prev_pages:'))
self.add_item(PaginationButton(pagination_step=-1, custom_id='prev_page', emoji=':prev_page:'))
self.add_item(PaginationButton(pagination_step=1, custom_id='next_page', emoji=':next_page:'))
self.add_item(PaginationButton(pagination_step=5, custom_id='next_pages', emoji=':next_pages:'))
@discord.ui.button(emoji=':close_x:', style=discord.ButtonStyle.danger)
async def close_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.message.delete()
You probably don't want to mix and match add_item with the @ui.button decorator
i also tried this way to add close button but that doesnt work either. when i click on button callback is called but message with view isnt deleted. can you recommend another solution for what i want to do?
def add_buttons(self):
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
close_btn = discord.ui.Button(...)
close_btn.callback = self.close_button_callback
self.add_item(close_btn)
async def close_button_callback(self, interaction: discord.Interaction):
await interaction.message.delete()
But you can remove and add them in the order you want to
Definitely don't monkeypatch
self.clear_items()
...
self.add_item(self.close_button)
self.add_item(...)
...
what is self.close_button? can you show example how should i do it
how can i add callback for button without using "monkeypatch"?
You are already making buttons without monkeypatching
we are talking about my last message where i used this #discord-bots message
but i dont want to create new button class that will implement discord.ui.Button for only 1 button
Is there a better way to write line 26?
import os
from dotenv import load_dotenv
import discord
import ollama
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('jeb ') or message.content.startswith('Jeb') or message.content.startswith('JEB') or message.content.startswith('jim') or message.content.startswith('Jim') or message.content.startswith('jebot') or message.content.startswith('JEBot'):
print("full message = " + message.content)
User_LLM_Input = message.content.replace('jeb ', '')
print("LLM input = " + User_LLM_Input)
LLM_Output = ollama.chat(model='gemma:2b', messages=[
{
'role': 'user',
'content': User_LLM_Input,
},
])
print(LLM_Output)
await message.channel.send(LLM_Output['message']['content'])
client.run(TOKEN)
Oops here is line 26
if message.content.startswith('jeb ') or message.content.startswith('Jeb') or message.content.startswith('JEB') or message.content.startswith('jim') or message.content.startswith('Jim') or message.content.startswith('jebot') or message.content.startswith('JEBot'):
i understood that by self.close_button you meant function to which decorator was applied. thank you its working now
def add_buttons(self):
self.clear_items()
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
self.add_item(PaginationButton(...))
self.add_item(self.close_button)
@discord.ui.button(...)
async def close_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.message.delete()
try someth like this
prefixes = ['jeb', 'jim']
if message.content.lower().startswith(tuple(prefixes)):
pass
Epic, thank you.
i would advise you to make a separate command for this. this is not best way to use on_message event for your task
i dont really know how to do that
ask chatgpt https://chatgpt.com/ or google it. there is really lot of examples how to make your own command
you can also set several prefixes for your bot or aliases for command
use the built-in command extension. see command walkthrough
it also support multiple prefixes
oh i see you want me to trigger it with a command
i think this is fine for now
I do have another question though, how do i make it show the thing that appears when another user is typing while the LLM is generating?
@bot.tree.command(name="bm",description="bookmarks the content")
async def add_bookmark(interaction: discord.Interaction, bookmarklink: str):
with open("bookmarks.json",mode="r",encoding="utf-8") as bookmark_store:
bookmark = json.load(bookmark_store)
user = interaction.user
user = str(user)
print(user,bookmark)
if user not in bookmark:
bookmark[user] = []
with open("bookmarks.json",mode="r+",encoding="utf-8") as bookmark_store:
bookmark[user].append(bookmarklink)
json.dump(bookmark,bookmark_store)
await interaction.response.send_message("Bookmark saved")``` is this ok for a bookmark feature .. now i already created a json file with {} present in it .. is this approach good?
how to set bot status like , playing game , watching
not sure but might be something like this
activity = discord.Streaming(name="Minecraft", url="https://www.twitch.tv/Minecraft")
await bot.change_presence(activity=activity)
found this
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))
# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))
# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))
# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))```
as i see , my code is correct but still it is not working
hm
so do you have any idea , what should i do now
activity = discord.Game(name="Minecraft")
await bot.change_presence(activity=activity, status=discord.Status.do_not_disturb)```
that works for me
do you use any other module for this .?
this is the code i used to test it
https://paste.pythondiscord.com/K7TQ
@barren forum
oh wait i m trying , btw thanks , i think i should write this command below the print
let's see
how to add subcommands here
?
like i need /bm add /bm view /bm delete
not sure, i'm not that good with slash commands
would prob be like options/choices for the add,view,delete ig
its not that hard
before defining your commands, you need to define the group
for example, your group would be
bm
oh but then i could like add mode = None in my above function and make conditions for it ig
oh
so literally you'd do bm = discord.app_commands.Group(name="bm", description="bookmark commands")
there isnt bot.tree.group
then you do
@bm.command(name="add", description="adds a bookmark") for ur command
this is how its set up in my cog
this return a Group but like this my whole code ```py
class Bot(discord.ext.commands.Bot):
def init(self):
intents = discord.Intents.all()
super().init(
intents=intents, command_prefix=discord.ext.commands.when_mentioned
)
async def on_ready(self):
print("running")
await self.tree.sync()
bot = Bot()
@bot.tree.command(name="hi",description="Says hi")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("hi there")
@bot.tree.command(name="bm",description="bookmarks the content")
async def add_bookmark(interaction: discord.Interaction, bookmarklink: str):
with open("bookmarks.json",mode="r",encoding="utf-8") as bookmark_store:
bookmark = json.load(bookmark_store)
user = interaction.user
user = str(user)
print(user,bookmark)
if user not in bookmark:
bookmark[user] = []
with open("bookmarks.json",mode="r+",encoding="utf-8") as bookmark_store:
bookmark[user].append(bookmarklink)
json.dump(bookmark,bookmark_store)
await interaction.response.send_message("Bookmark saved")
@bot.group(name="mygroup")
async def bot_grp(interaction: discord.Interaction):
pass
bot.run(token)``` i am not using app_commands
ignore last line
but now bot_grp.tree doesnt work
ah
is there someplace where i can really understand this library i just started yesterday
yea im looking docs but still like too many ways to do things
no that's not what i'm saying, i'm saying don't sync in the function on_ready
okay bye 👋
i got it from the docs i think
in thier examples
instead of syncing on_ready you should sync whenever you make a change
https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
when you sync on_ready you sync every time you run your python program, you'll get ratelimited really quickly
ohh
never used tree commands
yeah i don't even know what a tree is, i just use app_commands
as far as i know they're the exact same
but im seeing this
https://stackoverflow.com/questions/77958066/how-do-i-add-subcommand-support-with-discord-py
and the solution is to use app commands LMAO
okh ill look app_commands then.. but thier examples is full of tree commands
from discord.ext import commands
import discord.utils
intents = discord.Intents.default()
intents.members = True
intents.typing = True
intents.presences = True
intents.message_content = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.tree.error
async def on_app_error(interaction, error):
if isinstance(error, discord.app_commands.MissingAnyRole):
response = discord.Embed(title="Error", color=0xf54242)
response.add_field(name="", value="You dont have perms for this!", inline=True)
response.set_footer(text="PTV")
await interaction.response.send_message(embed=response)
else:
raise error
@client.command()
async def sync(ctx):
synced = await client.tree.sync()
print(synced)
@client.event
async def setup_hook():
# await client.load_extension("commands.user")
# await client.load_extension("commands.clock")
await client.load_extension("commands.admin")
@client.event
async def on_ready():
print('The bot is on!')
client.run('YOUR TOKEN') ```
This is my bot.py file
i use cogs to be more organized, its really helpful
woah why do you need every privileged intent
its for my roleplay server, I do a lot of stuff with the bot, change roles and nicks, use messages for things, etc
since its for my server specifically I dont care, its easer since I have ADHD and might forget to add them when needed
@bot.event
async def setup_hook() -> None:
global keep_moving
keep_moving = False
await setup_database()
print(await set_current_group_id())
while not current_group_id:
r_db.start(
current_group_id
) if not r_db.is_running() and current_group_id else None
db_online_loop.start(
current_group_id
) if not db_online_loop.is_running() and current_group_id else None
await load_cogs(bot)
async def load_cogs(bot: Bot, directory: Optional[str] = "cogs"):
for filename in os.listdir(directory):
if filename.endswith(".py"):
cog: str = f"{directory}.{filename[:-3]}"
try:
await bot.load_extension(cog)
print(f"Loaded extension: {cog}")
except Exception as e:
print(f"Failed to load extension {cog}: {e}")
i like to dynamically load cogs
it looks like you only have two cogs so you don't need to do that
I have like 6-7, but i just deleted them in the one i sent for simplicity
how does it work?
oh i thought it looked pretty simple to read
the thing is, specially with testing, its easier for me to disable every cog i dont neet in that moment
just comment it out and thats it
i see
but that looks super cool though!
in my case, i need every Cog to be loaded at the same time
ooo why?
lmao, fair
guess its useful if you're setting up multiple cogs and you change things constantly
mind if i test it in my bot?
no i don't mind, i really don't care if you took some code from me
smh i'm really bad at english
dw, me too
idk what is a cog is it the client.load() thing that loads it? is it like grouped slash commands?
ok got it
class Miscellaneous(Cog):
"""
Miscellaneous commands
"""
def __init__(self, bot: Bot) -> None:
self.bot = bot
async def setup(bot: Bot):
await bot.add_cog(Miscellaneous(bot))
basic structure of a Cog with no commands
actually if you use the default discord help command, that docstring gets added as a description of the Cog
why my bot status is not showing ?
You should not be using on_ready for this. It fires repeatedly and randomly. You can pass initial presence into the bot constructor instead
can i make a command both a context menu command and a slash command?
Given that they support disjoint parameters it's unclear how that would even work
Unless you're trying to make a slash command that accepts a member
can you write the code?
it's okay bro i have no idea what the hell bro is talking baout either
!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, ...)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#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) 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) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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\.
You can pass activity and status in when creating your bot
^ no idea what this guy is trying to say
yup , and i did it still It is not working
why you hating
do you not know how to pass in arguments to constructors
I’m not, I just don’t know what that guy is trying to say
Now that he said I’m hating now I have no idea what this guy is trying to say ^
😂
I mean. You could ask a targeted question
Let's explain it in baby language:
❌ VERY BAD:
bot = commands.Bot(
command_prefix=...,
intents=...,
)
@bot.event
async def on_ready():
await ...change_presences(activity=..., status=...)
# discord:
on_ready()
.. # after 5 secs
on_ready()
# maybe discord: why tf are you changing presences here, fuck off, <bot dies>
on_ready()
... # after 3 hours
on_ready()
..
on_ready()
on_ready()
# maybe discord: why tf are you changing presences here, fuck off, <bot dies>
on_ready()
...
✅ VERY GOOD:
bot = commands.Bot(
command_prefix=...,
intents=...,
activity=...,
status=...
)
# discord: oh you want the startup activity to be x and status y? That's easy!
for msg in channel.history(limit=5000):
Any idea why this prints as not iterable?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
There's a usage example in there
guys how can we get current time of the user calling the command?
Can't
Reliably
nvm i found
inter.created_at
That's the time the interaction was created it in utc
Not at all connected to the user lol
isn't that the time of interaction created by user?
Discord creates and sends interactions
hey there, is just 1vCore to low for a discord bot with a ticket feature and little other features?
not at all
but really it depends on the scale of your bot
if it's being used by a lot of users concurrently, consider scaling up
The only way to reasonably answer this remotely accurately is to run your thing and profile it
How do i fix Numpy is not avalible
not rly related to discord bots, try #1035199133436354600
it's a private bot
then yeah 1vcore should be fine
thank you
in discord.py:
i have a dropdown class:
class Shape_dropdown(discord.ui.Select):
def __init__(self):
...
async def callback(self, interaction: discord.Interaction):
if not str(interaction.user.id) in self.custom_id:
#what should i do here?
else:
#do stuff
now i want the dropdown to not update if the user is not permitted (the allowed user are in the custom id). how can i do it?
i didn't even find a way to see what was previously selected
the problem is that discord.py automatically updates the dropdown for you, i want to stop it from happening when a condition is met
It doesn't though
dropdowns (and modals) are updated by discord.py automatically.
https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=callback#discord.ui.Select.callback
i want to to disable it, how can i do it?
They are not
discord.py does not make discord api calls (generally) behind your back, and not in this case
What you implement in the callback is what happens. If you implement nothing, nothing happens
you're right......,this is what i found out:
if u select something on select dropdown, discord client will show it as selected even if the bot did not update the dropdown
u can see in the left is where i triggered the command, and in the right i tried to change the selected color, and it does update there. a simple reload to the right side resets it

Hello
Discord has added emojis built in bot, But i am having trouble using them.
Using them as normal emojis, What's wrong?
Ah apologies, i forgot the :
The name isn't important fwiw
<:_:ID> works everywhere
im trying to make my bot reply to a message instead of message.channel.send anyone know how?
Have you tried message.reply?
yeah
I just made a small mistake, didnt notice that.
That should reply to the message
2024-07-22 09:45:25 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "/home/caleb/python-projects/bot/.venv/lib64/python3.11/site-packages/discord/client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "/home/caleb/python-projects/bot/main.py", line 51, in on_message
await message.channel.reply(LLM_Output['message']['content'])
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'TextChannel' object has no attribute 'reply'
Could you send a snippet of your code?
await message.channel.reply(LLM_Output['message']['content'])
print('output: ' + (LLM_Output['message']['content']))
Also that says text channel has no attribute for textchannel, means your message is a channel
I mean for reply, sorry im on phone
You can only reply to a message, you are replying to a channel
You need to ensure the channel you want, and reply to the expected message
What i mean in your code you should have a function that defines the channel you want.
if not channel.id == `channel id here`:
return
This will check for the channel you want, and ensure all the actions happen in the mentioned channel.
Just message.reply
await message.reply(LLM_Output['message']['content'])```
seems to work thanks
:D
No worries 
One more thing i need help with, you know how when someone types it says they're typing? How can i make that appear while the LLM is generating?
Ah that's simple.
!d discord.ext.commands.Context.typing
async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.
In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer) call and does not do any typing calls.
Example Usage:
```py
async with channel.typing():
# simulate something heavy
await asyncio.sleep(20)
await channel.send('Done!')
```...
For example you can do
async with ctx.typing():
await asyncio sleep(5)
await ctx.send("here's your response")
I had it

😔
If it's an interaction command / You can do interaction.typing(): instead of ctx. @spiral kiln
Can you send me the entire command? So i can make you a proper example?
I just would like to see the command parameters.
if message.content.lower().startswith('jim'):
``` Its called jim as part of an inside joke.
Either way, this is what you need.
what are the things I should check/do before releasing the bot?
And it will stop typing when the LLM is done?
awesome
i still dont understand async/await lol
or even with
Is there a discord bot active currently which sends telegram channel msg to the discord server channel?
Active bot? Code is available on internet but I can't host it.
It is the best way to forward all your Telegram chats to Discord channel threads or use it as your customer support bot.
see their demo video
It's kind of different thing
sends msg from telegram bot chatting to discord channel
I want from telegram channel to discord channel
correct me if that bot is not this
oh sorry
np, chill
I'm trying to update the image inside an embed, that's inside a discord.View, but there's no file argument in the edit_message function
This is how the embed is originally created
Is it just not possible to update the image inside an embed, or is there some other way of doing this?
Check the parameters on InteractionResponse.edit_message
There is no file parameter. Would there be some way to do this with attachments?

That is the list of attachments that will be on the message after the edit. It accepts existing Attachments or new Files
Woah, it works now. I thought I tried that before, but maybe I did something wrong last time
Thanks!!
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.
If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.
If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.
See /usr/share/doc/python3.11/README.venv for more information.
note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.```
everytime i do `pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib` it gives me this error. Its only in command prompt tho when i do it in vscode it works fine.
apt install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package google-api-python-client
E: Unable to locate package google-auth-httplib2
E: Unable to locate package google-auth-oauthlib```
and thats what happens if i try apt like it told me to
did you try creating a venv?
yeah but then its making me re install everything else and i have to go in venv everytime to start the bot
nvm i fixed it
I just use the —break-system-packages option
yeah thats how i fixed it
Guys how can I get user's current time when the interaction takes place?
I wana get messages past x hours in a channel based on users time
I'd use .env
ive been using my config.toml for the token too, but either way you'd want to configure the file's permissions
Hello, is it possible to reply to a message with a webhook?
For example we put the message id as a paremeter of the command, And possibly replying to the message with a webhook.
no
webhooks send messages. they're boring and can't do anything
@context_menu(*, name=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command context menu from a regular function directly under this tree.
This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.
Examples...
Is there a way to know with which invite link user joined the server?
Mainly i want to get the user object
There isn't anything in the api for that but you can store all invite links across all guilds and check for their use counts. And when a user joins a server check which of the user invites gets incremented, and thats the inviter
But in some cases it won't work though
: ( not reliable then
Yeah and there's no other way
But discord alr provides this feature in the app itself
So it's just reinventing the wheel in a worser way
Actually we need that for an event
We are hosting an event in which people who invite more will get something
So we need to maintain leaderboard
But the problem we are facing if someone left then discord invite count doesn't decreases
So we don't know exactly how many people stayed
You'll have to keep track of the members the user invites
Hmm
Just append it to a list or smt
Well yea
Guys does interaction created_at tells time based on discord server or user's timezone?
Do you know if it returns a long/bigint or if its a date?
Because if it is a long i would guess its millisecond since epoch https://currentmillis.com/
thats not my question?
!d discord.Interaction.created_at
property created_at```
When the interaction was created.
maybe discord.dev has more info
cant find it
you could just do a test and change your computer date
and see if it changed
that returns server time not user's
i am not understanding your question then
In general, discord is not going to tell you where a user lives
i wana create a command to get messages past 3 hours of a user
so i need to get the local time of a user
it doesnt matter the time of the user for that
so how do i get messges past 3 hours when the command ran?
just use your datetime
that would be wrong as my time and user's time are different
yeah but it doesnt work like that
their messages are shown in your time
so -3 hours would still work because it would be the same offset
can you give one example?
which hour do my messages appear to you?
you mean time? 5:09 PM
its 1.49pm for me
oh , so what do you wana tell me through this?
how do i fetch last 3 hours of messages? thats my question
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
ik but it would return all messages
i mean where do i tell it to get only past three hours?
kk, imma try
offset = datetime.datetime.now() - datetime.timedelta(hours=3)
async for message in channel.history(after=offset):
if message.author.id != 123123123:
continue
# DO STUFF WITH MESSAGE
that should work
lemme find my message with more details (from a few years ago) and i'll tell you more about the RAM usage
oki
oki so i can't share the code because it's not mine to share (will ask the person who made it), but basically if you monkey patch discord.py to prevent it from storing voice/category channels as well as make it drop channel overwrite objects, you can save a lot of RAM
here's a rough amount of memory in KB used post-patching, it was significantly more before
Hey if i have 2 files in one is class that sends embed asking for deal amount in $ and then when user gives number it sends new embed with buttons (that class is in another file) and it asks if correct or incorrect, now i wanna code if it's incorrect to reset proccess and come back to first embed that asked for amount and to listen again for number
i think overwrites were like 4-5x more, and you can't even see voice channels now
if your only goal is to save RAM and you don't particularly care about maintenance burden/newer discord.py features, i can't recommend it high enough
okay here is code
https://paste.pythondiscord.com/XHLQ, 1st file is the class that asks for amount in usd, 2nd file is class that has correct and incorrect button
i want it to coem back to first class if button incorrect is clicked
Which one website link??
oh?
that discord invite is to the host I use itself
just ignore it in the image
sadly I do not install discord.py without voice (I probably should though).
since both of my bots don’t have voice support
refer it
well yeah you could fork it and make the changes and install from the fork though
You're recommending a djs guide in a python server?
Having a bit of trouble with using buttons, think maybe some of the language changed around these but having trouble making sense of the documentation. Trying to send a message with buttons but I keep getting this error
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Button.__init__() got an unexpected keyword argument 'style'```
This is the code I am using for the specific extension
```py
import discord
import datetime
from discord.ext import commands
from discord import Button, ButtonStyle
class Joinverification(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(1230669525645660180)
await channel.send(
f"Welcome {member.mention} to the server! What would you like to do?",
components=[
[
Button(style=ButtonStyle.green, label="Option 1"),
Button(style=ButtonStyle.blue, label="Option 2"),
Button(style=ButtonStyle.red, label="Option 3"),
]
]
)
@commands.Cog.listener()
async def on_button_click(interaction):
member = interaction.author
if interaction.component.label == "Just Visiting":
await interaction.send("You clicked Option 1!")
elif interaction.component.label == "Member of an allied org":
await interaction.send("You clicked Option 1!")
elif interaction.component.label == "Option 3":
await interaction.send("You clicked Option 1!")
async def setup(bot):
await bot.add_cog(Joinverification(bot))```
Any assistance would be MAJORLY appreciated
Which library are you using?
python 3.12.3 if thats the one you are looking for
Which discord library? Like what you're installing through pip
Sorry, 2.4.0
2.4.0 of what library?
Oh, well that explains why I was having trouble
Alternate library you would recommend?
I would personally recommend doing discord.py's way of doing buttons, which is with View classes
it does support it, just not in this way (which imo is much hackier)
Ok got it, the view classes was what I was finding and struggling with. That just requires defining the view before the command and whatnot yeah?
Well you could define it anywhere you could define a normal python class
then just instantiate it and send it in your command
Got it, ok I will work on going that direction. Thank you VERY much Solstice!
any time. The examples in the repo are quite extensive

Just confirming, if I was using this in an extension could I define the view ahead of the cog being defined or would that throw things off given they are both classes?
Or would I be better off defining it after the cog/extension has been defined
Think I have the button part figured out, just using some of the example code in the repo to see if its working but.....the message simply isn't sending....feel like I am missing something obvious
import discord
from discord.ext import commands
from discord import Button, ButtonStyle
class joinverification(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
channel = await self.bot.try_channel(978421363884818472)
view = Buttons()
await channel.send(f"Welcome to the server! {member.mention}", view=view)
class Buttons(discord.ui.View):
def __init__(self, *, timeout=180):
super().__init__(timeout=timeout)
@discord.ui.button(label="Blurple Button",style=discord.ButtonStyle.blurple) # or .primary
async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Gray Button",style=discord.ButtonStyle.gray) # or .secondary/.grey
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Green Button",style=discord.ButtonStyle.green) # or .success
async def green_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Red Button",style=discord.ButtonStyle.red) # or .danger
async def red_button(self,button:discord.ui.Button,interaction:discord.Interaction):
button.disabled=True
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Change All",style=discord.ButtonStyle.success)
async def color_changing_button(self,child:discord.ui.Button,interaction:discord.Interaction):
for child in self.children:
child.disabled=True
await interaction.response.edit_message(view=self)
async def setup(bot):
await bot.add_cog(joinverification(bot))```
Question for opinions
Would you all rather:
- Enter 4 channelnames into a slash command and get 4 channels created outside any categories
OR - Enter one category name and get the category with default channelnames
NOTE: all channels belong to the same feature
of course either way setup with the configured permissions
Personally, have the channels created with default names rather than having to enter all 4 but the entering all 4 would be convenient to do it in all one command I suppose
What is try_channel?

thats the obvious thing I was missing
it should be get channel
That should error though
Yeah not throwing any errors, still not throwing any errors with the get channel correction
Super weird
Are you logging anything at all?
Not a thing
You probably aren't enabling logging. How are you starting the bot?
py __main__.py
In code, how do you make the bot object and then start/run it?
def main() -> None:
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
if not DISCORD_TOKEN:
raise InvalidTokenException("A Discord token was not set.")
with open("config.toml", "rb") as config_file:
config = Config(tomllib.load(config_file))
bot = Bot(config)
bot.run(DISCORD_TOKEN)
Hope that is what you mean
Nope, everything else in the bot is working perfectly fine so no overall issues but yeah it doesn't throw any error codes
Interesting....I added a print line to say when the cog is ready but its not sending that
So I don't think its reading the extension at all
I'd recommend putting in some logging
import tomllib
import os
from dotenv import load_dotenv
from bot import Bot
from utils import Config
import logging
logging.basicConfig(level=logging.INFO)
class InvalidTokenException(Exception):
pass
def main() -> None:
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
if not DISCORD_TOKEN:
raise InvalidTokenException("A Discord token was not set.")
with open("config.toml", "rb") as config_file:
config = Config(tomllib.load(config_file))
bot = Bot(config)
bot.run(DISCORD_TOKEN)
async def on_ready(self):
print(f'{self.qualified_name} loaded')
logging.info(f'Logged in as {self.bot.user.name} ({self.bot.user.id})')
if __name__ == "__main__":
load_dotenv()
main()```
would this do the trick?
I know I need some additional stuff on the commands themself of course
Oh interesting, I moved the button class before it defines the cog itself and its finally sending the print message I put in at the end of the extension.....that being said the listener event itself still isn't working
At least I know its reading the extension
What is Bot?
How to separate Category in the on_guild_channel_update from Channels and Categories?
Because they seem to be together which is stupid 
first testings 😄
Categories are channels. If you care about a subset of channels, that's up to you to do that filtering based on the channel type
How do i disable one button, only for the guy who clicked on it?
help lets say i have a command adv but it needs to be adv (item) but the user just types adv, it just gives me an error how can i change it so that if no (item) is given i send a message that you need and item, how would i do that?
is it a prefix command?
if not args send message and return
i'm not even going to attempt to write the code for you, it's just basic python
This isn't how the library works. You don't get into the function at all if the user doesn't submit required arguments. The recommended approach is to make an error handler, either local to the command or global
? You give the parameter an Optional type hint and give it a default value of None
Wdym by “that’s not how it works”
Why would u make it optional if ur end goal is to make it required? you see how incorrect that logically is? it's better to make an error handler and handle the error raised when arguments are missing.
Because try except blocks take up too many indents
Error handlers don't have try excepts
There doesn't need to be a try except block
An error handler typically uses if statements
Also the optionality of a parameter changes how it's displayed in help text. Making it optional to avoid needing to make an error handler would also mislead the user looking at the command's usage
right
just have smarter users
add member intent
Can I add multiple databases in a single .db file?
I mean you can have multiple tables
If that’s what you mean
I would show you if I had access to my DB browser rn
Can someone help me with this error
Ye
!paste code pls
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
what are the python packages in this environment and their versions?
https://discordpy.readthedocs.io/en/stable/api.html?highlight=webhook#discord.TextChannel.create_webhook you don't need to supply a session to create a webhook
also Bot.session isn't a thing
So what can I do
just don't include the session arg when creating a webhook
Dpy 3.9.5
What the heck
That's not a thing that exists
I think python 3.9.5 ye
actually you need to supply session when using asyncio session when creating webhjook frmo url
but not when you are using TextChannel.create_webhook
Dpy 2.3.2
It would also generally be helpful to have a traceback for any errors. Just the exception text isn't particularly useful
So there I wrote session=bot.session so I will remove that?
yep
Irrelevant but I have the Linux kernel 6.11 btw
Who uses Linux fr
Me casually coding in a Android lmao
Bruh just do that on your computer 😭
I can only imagine the suffering
Yeah i suffer alot alot
I already struggle enough with regular typing on a mobile phone
Nahh im fast typing in mobile
I can’t imagine having to type brackets
An error occurred: session or client must be given @merry cliff
You can pass the bot into client=
Ohk wait lemme try
So how will I do that?
client= what
the bot
try it and see
@fast osprey also I have a file called botpfp.jpg so how can I read that and put it as webhook avatar?
I did before but I forgot
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2\.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
image=read(botpfp.jpg)?
Nah I’m wrong
Webhook create not send
I did client=bot and same error is coming still
Code and error?
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
Changed in version 1\.1: Added the `reason` keyword\-only parameter.
Wait
https://paste.pythondiscord.com/ZU7Q @fast osprey
So what do I do
Don't pass it in
If I don't it says it requires it
client= is a parameter to Webhook.from_url. You're calling entirely different methods here
webhook = await channel.create_webhook(name="BitBot Logging",client=bot) this is incorrect
you do not need it
just create it with the name
Webhook.from_url is a static class method, it needs to be told the client (bot) that's attached to it (or an aiohttp session).
channel.create_webhook is an instance method on an instance of a channel, which is already attached to your client (bot)
https://discordpy.readthedocs.io/en/stable/api.html?highlight=webhook from_url#discord.Webhook.from_url yeah client should be given here
https://paste.pythondiscord.com/X6KQ
@merry cliff this is updated code still not working
See sentence 1
I did that tho
You did not
Why do you keep explaining your code in your comments smh
Just say what the code does in a docstring
webhook = discord.Webhook.from_url(old_webhook_url)
Oh that ok wait
Also "not working" isn't particularly helpful, and once again, you need to get yourself tracebacks if you are going to debug properly
otherwise you are just going to have to look over your entire code base trying to find where the problem is rather than your code telling you
And that is the reason why someone needs to build the rust compiler, but for Python
Looking over, this is just a matter of them doing a blanket try, except Exception and then throwing away the traceback
Use io.BytesIO()
You need a bytes object
Is there a legitimate reason to do this here? I've been told to never do that
In this case, no. Blanket catches really should only exist in the highest level safety net error handling, which discord.py already has
Oh look it's mudkip.
Yeah tried that, no such luck.
Code?
Is dpy alligned with the new feature of bot emojis? If yes do you have docs for that?
What about them?
Well there is a new tab emojis in dev portal so I was wondering how we can get those emojis
"Get" as in send them in a message?
Yes
You should be able to send them like you do any emoji afaik, library independent
<:emoji_name:id>
Ohk also I get the id from?
On that tab in the dev portal
Ye
I'm developing a discord bot using discord.py. In this block of code, I'm trying to open a select menu after pressing a button. It should go though all available items in csv file (item is availabl...
could anyone help?
wdym it doesn't
what else should be there?
Ask @fast osprey
@fast osprey please
You can't use the @ui.select decorator for dynamic options
Well, at least you can't pass a dynamic list into the decorator itself. You could either make a Select subclass, or use the decorator and modify its options in the view's init
Either way, that list of options should be passed into the view, not accessed from a class attribute like you have
How do I make a bot start, I am new to using python
Check dpy docs
heh
class ItemSelectMenu(ui.View):
def __init__(self, *, timeout=None):
super().__init__(timeout=timeout)
self.options = [discord.SelectOption(label=item) for item in ItemButtonMenu.available_items]
@ui.select(placeholder='Choose an item', options=self.options)
async def item_select(self, select: ui.Select, interaction: discord.Interaction):
pass
do you mean like that? i dont get it
You can't reference dynamic attributes in the decorator
but i dont get how to fix this
i mean available_items is always gonna change
One of these two methods
i did modify its options in the view's init
or you meant something else
You didn't
You set a property on the view named options
In the init, self.options is setting an attribute on the view itself. self.item_select is the Select itself
class WelcomeView(View):
def __init__(self, member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id):
super().__init__(timeout=None)
self.member = member
self.recruitment_role_id = recruitment_role_id
self.external_affairs_role_id = external_affairs_role_id
self.visitor_role_id = visitor_role_id
self.new_join_role_id = new_join_role_id
@discord.ui.button(label="Open Recruitment Thread", style=discord.ButtonStyle.primary)
async def open_recruitment_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
recruitment_role = interaction.guild.get_role(self.recruitment_role_id)
if recruitment_role:
try:
thread = await interaction.channel.create_thread(
name=f"Private thread with {recruitment_role.name}",
auto_archive_duration=60,
type=discord.ChannelType.private_thread
)
await thread.add_user(self.member)
await thread.add_user(recruitment_role)
await interaction.followup.send(f"Private thread created with {recruitment_role.name}", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the recruitment role.", ephemeral=True)
@discord.ui.button(label="Open External Affairs Thread", style=discord.ButtonStyle.secondary)
async def open_external_affairs_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
external_affairs_role = interaction.guild.get_role(self.external_affairs_role_id)
if external_affairs_role:
try:
thread = await interaction.channel.create_thread(
name=f"Private thread with {external_affairs_role.name}",
auto_archive_duration=60,
type=discord.ChannelType.private_thread
)
await thread.add_user(self.member)
await thread.add_user(external_affairs_role)
await interaction.followup.send(f"Private thread created with {external_affairs_role.name}", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the external affairs role.", ephemeral=True)
@discord.ui.button(label="Assign Visitor Role", style=discord.ButtonStyle.success)
async def assign_visitor_role(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
visitor_role = interaction.guild.get_role(self.visitor_role_id)
new_join_role = interaction.guild.get_role(self.new_join_role_id)
if visitor_role and new_join_role:
try:
await self.member.add_roles(visitor_role)
await self.member.remove_roles(new_join_role)
await interaction.followup.send(f"Visitor role assigned and New Join role removed!", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to manage roles.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the specified roles.", ephemeral=True)```
class joinverification(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
channel_id = 1230669525645660180 # Replace with your channel ID
recruitment_role_id = 1198339491342065734 # Replace with your recruitment role ID
external_affairs_role_id = 1230668342235234324 # Replace with your external affairs role ID
visitor_role_id = 1081624269009715220 # Replace with your visitor role ID
new_join_role_id = 1265108242221236289 # Replace with your new join role ID
channel = self.bot.get_channel(channel_id)
if channel:
view = WelcomeView(member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id)
embed = discord.Embed(
title="Welcome to the Server!",
description=(
f"Hello {member.mention}, welcome to the server!\n\n"
"We're excited to have you here.\n\n"
"Feel free to explore and let us know if you have any questions.\n\n"
"Click the buttons below to get started!"
),
color=discord.Color.blue()
)
embed.set_image(url="https://example.com/welcome-image.png") # Replace with your image URL
await channel.send(embed=embed, view=view)
else:
print(f"Failed to find the channel with ID {channel_id}")```
INTENTS = discord.Intents.default()
INTENTS.message_content = True
INTENTS.members = True
INTENTS.guilds = True```
intents ^
I tried adding some steps that would call out why it wasn't working if it encountered an issue but nothing really changed
How is INTENTS being used?
Think I am a bit confused by that question
I am still learning so apologies for anything that is obvious that I am not getting
The code you sent just makes a variable named INTENTS
That doesn't do anything on its own
Oh oh oh
One moment
class Bot(commands.Bot):
def __init__(self, config: Config, /) -> None:
super().__init__(
intents=INTENTS,
command_prefix=commands.when_mentioned_or(config.prefix),
allowed_mentions=discord.AllowedMentions(everyone=False),
case_insensitive=True,
activity=discord.Activity(
type=discord.ActivityType.watching, name="Stanton"
),
)
self.config = config
self.version = VERSION```
And it's your on_member_join that isn't working? I'd suggest putting some logging in there
The on member join itself is working but the interaction is failing with all of the buttons
What is the exact set of steps you are doing for that to happen, and what do you see?
Are you referring to the actual interaction within Discord itself?
If so.
- Member Joins
- Message is sent in the proper channel upon them joining that tags the user and includes the 3 buttons
- Click any of the buttons
- Attached picture shows what I see
No errors in the terminal.
Those buttons are different than the view class you just sent
I changed the labels of them but the code is the same
I can send the code in its current form for the view
Send the code you are using currently please yes
Yup yup
class WelcomeView(View):
def __init__(self, member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id):
super().__init__(timeout=None)
self.member = member
self.recruitment_role_id = recruitment_role_id
self.external_affairs_role_id = external_affairs_role_id
self.visitor_role_id = visitor_role_id
self.new_join_role_id = new_join_role_id
@discord.ui.button(label="Join Gjallarhorn", style=discord.ButtonStyle.primary)
async def open_recruitment_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
recruitment_role = interaction.guild.get_role(self.recruitment_role_id)
if recruitment_role:
try:
thread = await interaction.channel.create_thread(
name=f"Private thread with {recruitment_role.name}",
auto_archive_duration=60,
type=discord.ChannelType.private_thread
)
await thread.add_user(self.member)
await thread.add_user(recruitment_role)
await interaction.followup.send(f"Private thread created with {recruitment_role.name}", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the recruitment role.", ephemeral=True)
@discord.ui.button(label="Member of an Allied Org", style=discord.ButtonStyle.secondary)
async def open_external_affairs_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
external_affairs_role = interaction.guild.get_role(self.external_affairs_role_id)
if external_affairs_role:
try:
thread = await interaction.channel.create_thread(
name=f"Private thread with {external_affairs_role.name}",
auto_archive_duration=60,
type=discord.ChannelType.private_thread
)
await thread.add_user(self.member)
await thread.add_user(external_affairs_role)
await interaction.followup.send(f"Private thread created with {external_affairs_role.name}", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the external affairs role.", ephemeral=True)
@discord.ui.button(label="Just Visiting", style=discord.ButtonStyle.success)
async def assign_visitor_role(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer(ephemeral=True)
visitor_role = interaction.guild.get_role(self.visitor_role_id)
new_join_role = interaction.guild.get_role(self.new_join_role_id)
if visitor_role and new_join_role:
try:
await self.member.add_roles(visitor_role)
await self.member.remove_roles(new_join_role)
await interaction.followup.send(f"Visitor role assigned and New Join role removed!", ephemeral=True)
except discord.Forbidden:
await interaction.followup.send("I do not have permission to manage roles.", ephemeral=True)
else:
await interaction.followup.send("Failed to find the specified roles.", ephemeral=True)```
Does that message pop up immediately after clicking the button, or after about 3 seconds?
Let me double check that, one moment
Also, could you paste everything you're getting in your terminal when you run the bot and do this?
Traceback (most recent call last):
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "D:\Bots\Sigmund\extensions\joinleave.py", line 17, in on_member_join
await channel.send(embed=embed)
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 758, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Not a well formed URL.```
This is weird, I don't think this error is related to the buttons not working
Just an issue with the thumbnail, which is still working
but that being said, it says interaction failed I'd say more immediately than within 3 seconds
No errors being thrown in the terminal when buttons fail
will ad logging and see what it says
First thing to check is if you have an interaction url in the discord dev panel
Oh, good call, will do
Yes it does have an interactions endpoint url if thats what you are referring to
If you aren't making an http interaction bot, you should remove that
You're hosting your bot in a place you shouldn't be
Because you are hosting your bot in a place you shouldn't be
no im using pylexnodes it can host bots
Clearly it cannot
Because something happened to work in the past does not mean it was the right decision, or that it will continue working
"Free" hosts are universally scams. It is not a sustainable business model
I did
I think it's because i made the sync commands thing inside on_ready
I forgot to remove it
That would not result in that error, but you also should not be putting basically anything in on_ready
Okay
Got it
Doing this broke the other member join stuff so will sort through that and try removing that link and see what it does
Setting that URL means that discord will post interactions to the URL you specify, rather than being sent as a gateway event (which is how discord.py and other libraries function)
welp, all my invites to my alt are now failing so gunna have to figure that out first lmao
miserable, i appreciate all your help though
Not really sure what you mean by "invites to my alt"
But if you can't really mix and match http interactions with gateway interactions (discord.py etc)
They get sent to one or the other
I use an alt to join the server to test the functionality but I keep getting hit with the "invalid invite" no matter what options I choose because I have been doing it so much
Super weird, this seemed to have introduced a new error that wasn't happening before. This is just for the basic member join notification to our welcome channel. Seems to be from the thumbnail.
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "D:\Bots\Sigmund\extensions\joinleave.py", line 17, in on_member_join
await channel.send(embed=embed)
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 758, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Not a well formed URL.```
Unrelated but, still annoying
@fast osprey removing that HTTP looks like it fixed it, its giving me some permissions error which I thought I had accounted for (easy fix) but no more interaction failed!!!
the above error is still an issue, but one I think I can fix

how do I make those button persistent?
wanted to add bot.add_view(ItemSelectMenu) and bot.add_view(ItemButtonMenu) to the on.ready event, but realized I need to pass available_itemsto ItemSelectMenu, and available_items is a list which values are defined in ItemButtonMenu. Is there any simple way to fix this? Or do i need to define available_items outside of ItemButtonMenu?
You shouldn't be using on_ready for things you want to happen reliably or once
I want to make buttons work even after reloading bot
so where should I add add_view then?
That said, if your bot originally relied on sending multiple view instances each with their own state, then you can't get away with just persisting a single view instance when the bot wakes up
Wherever you want it to trigger. But presumably that's not "randomly and repeatedly whenever the bot does a routine reconnection"
Your options here are:
- Remove the need for state, and have a singular view instance with no parameters handle all interactions on all messages matching that view
- Remember the state for each instance of the view (message) you're sending, then call add_view that many times passing in the message id so you can recreate that state
- Shift entirely away from persisting views to use dynamic items
It’s because that’s probably a shared IP address
Yeah I was thinking of that
how i can know via bot when someone boost the server?
There is not a definitive way, all you can do is guess
how about role check?
if someone role gets updated?
That wouldn't tell you if someone who already had the role boosted again
i dont think booster role is manually assignable
People can boost multiple times
only discord assigns it
i can skip if they already have the role
That methodology would not tell you if someone boosted a second time. They already have the role
Same with premium_since
role dont get away? if someone remove the boosts?
Huh
That's not the case I'm describing
Someone boosted earlier. They have the role and premium_since. They boost again. Your code doesn't see anything
The closest thing you can do is listen for the system message, but that also has false negatives
https://github.com/Rapptz/discord.py/issues/2397 will this solve the issue?
How can we check in disnake library if a user is already timed out?
!d discord.Member.timed_out_until
An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.
New in version 2.0.
i have firstview.py
and it has this function:
async def reset_embed(self, interaction):
if interaction.message.embeds and len(interaction.message.embeds) > 0:
embed = interaction.message.embeds[0]
if len(embed.fields) >= 2:
embed.set_field_at(0, name=f"Sending {self.currency}", value="`None`", inline=True)
embed.set_field_at(1, name=f"Receiving {self.currency}", value="`None`", inline=True)
else:
print("Not enough fields in the embed to reset.")
self.children[0].disabled = False
self.children[1].disabled = False
await interaction.message.edit(embed=embed)
else:
print("No embed found to reset.")
And that's for a reset button in specific embed, but there's like one more embed for confirmation after this(it's in another file, in class), that has incorrect and correct button, i want to pass reset_embed function to that incorrect button to do, so it resets the original embed and it deletes the interaction.message with that incorrect button, i hope soemone understood 😭
who can help for a discord bot in dms
i can give the code, i just can't make the discord bot
so i kinda need help or someone make it for me
i'm not too proud about my ability on discord bots but i can try to help u
dont dm please
either put the code here or in a #1035199133436354600 thread
o wait
im gotta be afk somethingirl
ok thanks
if u want to pass the reset function u can import and pass it ig 👀
Are you supposed to have several database files? Or should I have one with several tables?
You probably don't need multiple databases
How can interaction.response.send_message raise discord.errors.InteractionResponded: This interaction has already been responded to before, when interaction.is_expired returns False?
I've been debugging this for hours 😅
send code
are u deferring it?
if your deferring it you need to do interaction.followup.send
I'm not deferring it. Even deferring it raises the same issue
send the code then please
Give me a moment and I'll send a code snippet. It's for the Code Jam, so I'll make a small example from it rather than sharing the exact code
class QuestionView:
def __init__(self) -> None:
super().__init__()
self.next_interaction: Interaction | None = None
@discord.ui.button(
label="Incorrect answer",
style=discord.ButtonStyle.danger,
)
async def incorrect_answer(self, interaction: discord.Interaction, _: discord.ui.Button) -> None:
self.next_interaction = interaction
self.stop()
And this is the class that is using QuestionView: ```py
class Level(Protocol):
async def return_to_view(self, interaction):
...
await interaction.response.send_message(file=img, embed=embed, view=view)
async def run():
next_interaction = interaction
for question in self.questions:
question_view = question.view() # A QuestionView instance
await next_interaction.response.edit_message(
embed=question.embed(),
view=question_view,
attachments=[],
)
await question_view.wait()
next_interaction = question_view.next_interaction
await self.return_to_view(interaction)
There's more code in reality, but it should be unrelated. Basically what's happening is that when the discord UI button is pressed, the interaction is stored in QuestionView.next_interaction and the QuestionView is stopped. The Level class waits for QuestionView to be stopped and then gets the question_view.next_interaction in order to let the next question continue from that interaction
When all questions are looped through, self.return_to_view(interaction) uses the last interaction to return to a different view. However, this interaction fails for some reason. And I don't think it's been responded to, especially since interaction.is_expired is false if called right before the interaction.response.send_message
Seems like interaction.edit_original_response instead of interaction.response.send_message works, but Discord says Interaction failed in response to the button press? Wtf
You generally should not be storing interactions imo. They are very stateful and short lived, ideally they should be handled in the direct handler and then discarded
For a TextInput in a modal, is there a way to make the user's input have python code highlighting?
I'm able to change the style to paragraph, so it's accepting long input strings, but can't find a good way to get syntax highlighting to work
Not supported afaik
Do you know if there's a way to have a description in a modal, or any text field that the user can't edit? Can't find anything like that either
Does anybody here knows some good hosting for python bot that is on server with 8k members? I need it to have servers in EU, so it has low latency
You can have titles on each field, as well as placeholders (the grayed out text inside of them)
You should profile your bot's resource usage so you can make an informed decision
I litterally need any hosting that is good and will run 100% 24/7
but if reset function is inside the class?
And you can't answer that without knowing what your bot needs
FYI is_expired() only checks if it's 15min past the interaction's creation time, interaction.response.is_done() is what actually determines if you already responded to an interaction
Ah good to know, thanks
how to make different amount of decorators every time function is called?
What's the functional thing you're trying to accomplish?
I've got list: available_items: [['1', '2', '3', ..... '25'], ['26', '27', ..... '50], ...] and every time it's got different amount of items (between 1 and 4). I've also got a button, pressing which calls 4 SelectMenus. Every SelectMenu has its own options depending on items in available_items. The thing is, if available_items got less than 4 lists, it'll raise an error list index is out of range (because available_items[4] doesn't exist anymore).
I suck at explaining lemme provide code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Not sure what the decorators have to do with what you're asking
This feels just like logic you need to implement when you're setting those options
cause if available_items contains only 3 lists, the 4th SelectMenu shouldnt be called
or can i somehow disable it
?
You can disable the select yes
@client.command()
async def item(ctx):
view = ItemButtonMenu()
await ctx.send("Choose an option:", view=view)
class ItemButtonMenu(ui.View):
def __init__ (self, *, timeout=None):
self.available_items = []
self.available_items_for_user = []
super().__init__(timeout=timeout)
@ui.button(label = 'Take item', custom_id = 'take_item', style = discord.ButtonStyle.green)
async def take_item(self, interaction: discord.Interaction, button: ui.Button):
with open('items.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
self.available_items = [row[0] for row in csvreader if row[1] == '']
view = ItemSelectMenu(self.available_items)
await interaction.response.send_message(view=view, ephemeral=True)
class ItemSelectMenu(ui.View):
def __init__(self, available_items, timeout=None):
super().__init__(timeout=timeout)
def chunks(lst, n):
for i in range (0, len(lst), n):
yield lst[i:i+n]
self.children[0].disabled = True
self.children[1].disabled = True
self.children[2].disabled = True
self.children[3].disabled = True
for i in range(len(list(chunks(available_items, 25)))):
self.children[i].max_values = len(list(chunks(available_items, 25))[i])
self.children[i].options = [discord.SelectOption(label=item) for item in list(chunks(available_items, 25))[i]]
self.children[i].disabled = False
@ui.select(placeholder='Choose an item')
async def select_callback_0...
@ui.select(placeholder='Choose an item')
async def select_callback_1...
@ui.select(placeholder='Choose an item')
async def select_callback_2...
@ui.select(placeholder='Choose an item')
async def select_callback_3...
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "F:\Projects\discord-bot/main.py", line 135, in take_item
await interaction.response.send_message(view=view, ephemeral=True)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\interactions.py", line 855, in send_message
await adapter.create_interaction_response(
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\webhook\async_.py", line 223, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.3.components.0.options: This field is required
Why does it happen
You are sending over a select with no options
can options be empty?
Nope
@discord.ui.button(label="View Transaction", style=discord.ButtonStyle.link)
async def view_transaction(self, interaction: discord.Interaction, button):
button.url = f'https://etherscan.io/tx/{self.tx_hash}'
Is this right code for redirect button for embed discordbot
url buttons dont have a callback
alr
On member update, check the before and after roles. If they have the boost role after and didn't before they have boosted
i believe on message gives you the "member boosted the server" message, if you have that enabled
actually its not 😅
well that is unfortunate
help im new to cogs and somehow its not working
What about it isn't working?
Have you done any debugging to see what is happening?
If you're getting into that method at all?
add_cog is async, you need to await it
(as of discord.py 2.0+ and forks spun off of it)
You need a setup function
setup is only required in extensions