#discord-bots
1 messages · Page 331 of 1
Idk if we should use a different cursor for every transaction
how is it different? it returns the relevant cursor u can always close it manually or ignore it it gets cleaned up by gc automatically
both approaches are fine
gc means garbage collector? Right?
yeah
Sharing cursors can lead to incorrect data being retrieved
https://gist.github.com/sgtlaggy/9d43d5223314d559792ea6544673f1da
You should. Using a context manager is ideal so the cursor is always ideal for cleanup, and using a connection pool alongside it will help simplify queries
aiosqlite doesn't support connection pools and won't, so you'll need to switch to asqlite
@loud junco This is relevant to you as well
thats for only data fetched where a cursor is being returned as long as u use the common execution function there should be no issues
i've since had to move away from aiosqlite and had to move to postgresql.
aiosqlite is fun, and easy to use, but apparently not ideal if your bot is seeing lots of action
😢
Anyway. Hi @final iron
asyncpg op
class MyBot(commands.Bot):
async def setup_hook(self):
self.db = await aiosqlite.connect("sqlite3 ep.db")
async def execute(self, query, *args) -> aiosqlite.Cursor:
cursor = await self.db.execute(query, args)
await self.db.commit()
return cursor
```am i missing some important details why is it still not working 😭😭😭
In what way is it not working
Hi
Could you paste the whole code if possible
You definitely initialise bot from wrong class
You defined a class a never used it
Your bot needs to be
bot = MyBot(...)
Yeah what do you think you created class for
ok i just saw what ive been doing
too blind fr 😭😭😭
so this is correct right?
Seems so
This seems correct but what error do you get
Move code from async with bot to setup_hook method
music bot?
but if i move it there i have to change asyncio.run as well and i dont think im going to asyncio.run the method
Set it up, see if there’s any errors
Average aiosqlite experience
Use asqlite
It’s on GitHub
Aiosqlite doesn’t support connection pools so id highly recommend switching anyway
i tried changing it
im just giving up =.=
If you move it you don't even need asyncio.run
It will be bot.run
how did u create the .db file ? manually?
How do I make the the variable "name" obligatory here?
@app_commands.command(name = "newproject", description = "Create a new project")
async def newproject(self, interaction: discord.Interaction, name: str, description: str) -> None:
Mm asqlite won't unlock the db, it's clearly not the lib that is the cause
Give it a default value, like this
async def cmd(self, inter, name: str = "default name")
Pay attention that default value args go after args without default value
If by obligatory you mean optional yes
oh no, I mean that the command cannot be executed if that parameter is not given
Well this already implements such behaviour
You can't not give the argument, discord requires you to
Asqlite enables WAL by default which helps mitigate the locking
ya
i create a file call sqlite3 ep.db
use the command to create like
sqlite3 name.db
u need to run it in bash or cmd
did hydro switch to sqlite3 from the aoi thing
same stuff aoi is a cli wrapper around sqlite
oh lol
why doesnt he just use the sqlite3 package
does aoi have more functionality
it's you async
why is it so complicated i dont even know what to do now ;-;
.
Aoi is for db browsing, not db wrapper for usage in project
I had pretty much linked you a working project, no idea how you got so deeply confused
It's in disnake but the only difference is setup is done in start instead of setup_hook
No even need to do that, sqlite in py will automatically create database if it's missing on provided path
i see
@loud junco just read the BdayBot class, you will get what each line does and what the structure should be like, but make sure to read line by line
https://github.com/Exenifix/birthday-bot/blob/master/modules%2Fbot.py
how can i put bot.wait_for in always running while loop? Like a event
class BanAppeal(View):
def __init__(self, func, role:Role):
self.value = None
self.func = func
self.role = role
u forgot to call super().__init__(timeout=whatever)
now this problem
i fking hate my life
i for () these
if a bot is offline will the button go timeout even if the timeout is set to none?
if yes is there a way to reactivate the button
it will not respond to any interaction
persistent views
and how do i make that?
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
in short, give every button in your view a custom_id= alongside your None timeout, then add the view to your client during startup
i alr haev custom_id for every button
so basically i just add the view in the bot on setup hook?
umm
being honest i still dont get it
yes, by adding the view you're telling discord.py which components it can handle interactions from
yeah, you have to instantiate your BanAppeal view
wait what if i have requirements to put into my view
that's where it gets complicated, you have a "stateful" view
a what view
stateful means you have state, i.e. parameters/variables stored in your view that need to be restored after the bot restarts
you have a database already, so that's where you'd want to store it
well i have a ticket that have diffrent views for different buttons so how do i do that
it need to have the user of the tickets who opened it to let it close it
with difficulty
to make this more complicated i have an entire function as an input for my view so yea
a table for each type of view might be enough (containing the message ID and parameters for each ticket view), but you have to also delete the corresponding row in those tables once the view is no longer useful
what about the function how can i take that in a db
it should be serialized in some other way that makes it obvious which function you should use
sounds awful yea ill skip that
if your views are too complicated to re-create, you'll have to simplify them so its easier to make them persistent
well
i have an idea
basically i am using the BanAppeal thing for a button i can just make a command that clears the channel and adds a new view everytime someone is banned so i dont have to do all the things
Can someone help me finish this code please?
import discord
import requests
import os
from discord.ext import commands, tasks
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}')
@tasks.loop(minutes=15)
async def update_channel():
tiktok_account = "octo_tech"
follower_count = get_tiktok_follower_count(tiktok_account)
guild_id = 1094273879482060911
channel_id = 1177524750533267487
guild = bot.get_guild(guild_id)
channel = guild.get_channel(channel_id)
await channel.edit(name=f'TikTok Followers: {follower_count}')
def get_tiktok_follower_count(account)
@bot.command(name='start')
async def start_update(ctx):
update_channel.start()
await ctx.send('Updating voice channel name based on TikTok followers!')
@bot.command(name='stop')
async def stop_update(ctx):
update_channel.stop()
await ctx.send('Stopped updating voice channel name.')
token = os.environ['TOKEN']
bot.run(token)```
what do you wanna do with this
well you need to finish the tiktok follower count rest is good i think
well you need to use a api
tiktok dosent have an api does it?
https://github.com/davidteather/TikTok-Api u can try smn like this ig
this is the docs btw
Look at the various APIs, none will help you
how would i implement this one? i'm not the best at coding, only know the basics
There are examples..
yeah but i'd like direct help
The examples are exactly what you need and we can't be more precise than a code example you can literally copy paste. We don't code for you. Use them. They even have a Discord server linked, use it.
Know that Discord bots are also not made for people that only know the basics.
async def override_autocomplete(interaction: discord.Interaction,current: str,) -> List[app_commands.Choice[str]]:
keys_list = ['Budget', 'Bob', 'Income']
return [
app_commands.Choice(name=stat, value=stat)
for stat in keys_list if current in stat
]
@bot.tree.command(name="override", description="Overwrites a player's stats")
@app_commands.describe(player="Who do you want to override", stat="What do you want to override", override_value="What do you want to set the override to")
@app_commands.autocomplete(stat=override_autocomplete)
async def override(interaction: discord.Interaction, player: str, stat: str, override_value: str):
Can someone help, I dont know why this auto complete isnt working.
it should work dont see anything wrong tbh did u enter something in the autocomplete option to test?
one more check u can do is if current.lower() in stat.lower() ig
yes
what did u enter?
also u assigned it to autocomplete for stat
so make sure u check for the correct param
Tried it with that and it also didnt work.
no when typing B wait for a sec or two does no options pop up?
Nothin shows up
also add a print statement in the autocomplete function to see of its being triggered
omg i gotta be the dumbest guy alive
if this format dosent work u can try registering the autocomplete in the following manner
@override.autocomplete("stat")
??
I fixed it, I have two bots running with the same code, but one didnt have the autocomplete and I kept using that bots command instead of the other one
bruh
download it in thorght the vscode terminal
or just install it on the folder you are working on
ur running the code using python 3.11 u installed requests in python 3.12
You should also download Python from the actual website instead of the Microsoft store version
How can I create a command that creates a private channel between to players?
Id like the input to be a mention and it creates a chat between the player who ran the command and the mentioned player.
@bot.tree.command(name="diplomatic",description="Allows players to create a private chat with someone.")
async def diplomatic(interaction: discord.Interaction, player: str):
user_name = await id_to_username(player) # Assuming id_to_username takes an ID
user = interaction.guild.get_member(interaction.user.name)
# Create category if it doesn't exist
category_name = "Diplomatic"
category = discord.utils.get(interaction.guild.categories, name=category_name)
print(category)
if category is None:
category = await interaction.guild.create_category(category_name)
# Create a private channel for the mentioned members
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True),
user_name: discord.PermissionOverwrite(read_messages=True),
}
channel_name = f'{user}-{player}'
await interaction.guild.create_text_channel(name=channel_name,category=category_name)
await interaction.response.send_message(f"Created channel {channel_name}")
This is what I have so far
If I have a discord modal, is there a way to provide custom validation, or is it just a "something was incorrect, report and send a new modal" kinda situation?
Direct Messages already exist
This is kinda just reinventing the wheel
yeah but i need admins to see it to
What problem are you facing
me when people want to create the most privacy invading bot
Creating a new channel every time is going to severely limit the server and bot anyway
yeah that as well
Hence, direct messages
If i didn't use a gateway connection and instead i used http interactions would i still be able to get vc events?
no
how would that even work
cause i saw somewhere for a vc you make a new seperate gateway connection
and im wondering if vc events would come through there
Well, yes but you'd still be connected to the gateway
right but i could use vc's without the main gateway connection?
like the one that every other event comes through
You will still connect to the normal gateway at least once
To send the voice state update event and its relevant payload
guys i have noticed that bots that have been written with discord.js can now put their own status (not activity like watching, listening etc.). Did dpy got updated too or not? cause I can't find anything about it
Status has been available for a very long time
do you mean the "Set Custom Status" feature on your discord client? in dpy its known as CustomActivity
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
in that case dpy basically already supported custom statuses, but the API didn't allow it until a few months ago
https://discord.com/developers/docs/change-log#activity-state-for-bot-users
Swear it's been supported for longer
The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
is says i dont have python downloaded even though i do..?
Show that error, and the command you ran
I just did pip install discord.py
is says i dont have python downloaded
Doesn't say this anywhere
Prefix your command with py -m
It says I don’t have it downloaded mb
No it doesn't
Show that error
so py -m pip install discord.py
try it and see
yea that works
Can anyone help me with my python?
my pip doesnt work and whenever i try to install something it says "python is not reconized"
'python' is not recognized as an internal or external command,
operable program or batch file.```
Use py
even then i still cant install pip
just got a new pc and i cant install pip
Why do you need to install pip
Am trying to make a discord bot but now i cant install discord as a package
What's the error when you install it
it installs all the way untill this
ahh i see the issue
The error clearly says: This error originates from a subprocess, and is likely not a problem with pip.
Use this to install it pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/
isnt it caused by python 3.12 ?
ohhhh, I didn't know that. thank you alot :D
It’s correlated to 3.12, but not caused by it
yep
I think if you get the latest Microsoft c++ build tools ,the error should go?
pip instal ?
Ye
What are you trying to do with it?
Also semi colons are bad practice
You should know what to do with it?
Why does my bot not wait for the response?
embed = await self.create_message_embed("Reason for the report?")
await interaction.user.send(embed=embed)
reason = (await self.client.wait_for('message')).content
embed = await self.create_message_embed("Any evidence to provide? If so, provide it now, or type 'No'")
await interaction.user.send(embed=embed)
evidence = (await self.client.wait_for('message')).content
``` It sometimes does and sometimes doesnt
there's no check so it takes any message, in any channel, in any guild
In this code (part of a Cog), I would like that when any of the buttons are pressed, they remove the original message sent by the NewProject class and send another one indicating whether the creation was accepted or denied. If possible, the interaction should be edited. Is that possible?
class ConfirmationButtonView(discord.ui.View):
def __init__(self, timeout = None):
super().__init__(timeout = timeout)
self.value = None
@discord.ui.button(label = "Confirm", style = discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
self.value = True
self.stop()
@discord.ui.button(label = "Deny", style = discord.ButtonStyle.red)
async def deny(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
self.value = False
self.stop()
class NewProject(commands.Cog):
def __init__(self, bot: commands.Bot, config: dict) -> None:
self.bot = bot
self.category_id = config["categorys"][0]["id"]
@app_commands.command(name = "newproject", description = "Create a new project")
@app_commands.describe(name = "Name of the project", description = "Description of the project")
async def newproject(self, interaction: discord.Interaction, name: str, description: str, points: int) -> None:
guild = interaction.guild
questionEmbed = discord.Embed(title = "Alert ⚠", description = "A new project is about to be created with the following characteristics. Please check that everything is correct.", colour = discord.Colour.red())
questionEmbed.add_field(name = "Name", value = name, inline = True)
questionEmbed.add_field(name = 'Points', value = points, inline = True)
questionEmbed.add_field(name = "Description", value = description, inline = False)
questionEmbed.set_thumbnail(url = thumbail_url)
questionEmbed.set_footer(text=f"Interaction time - {current_time}")
#new_channel = await guild.create_text_channel(name = f"{name}", category = guild.get_channel(self.category_id))
await interaction.response.send_message(embed = questionEmbed, view = ConfirmationButtonView(timeout = None))
if you want to edit the original message you can simply use interaction.response.edit_message(), but if you want to delete the original message you should give the command's interaction to your view and call interaction.delete_original_response()
man. I hate this. why did I decide i wanted to make a discordbot..
btw (button, interaction) is the wrong order for the button callbacks, it should be (interaction, button)
Can I call the interaction.response.edit_message() directly from the button?
client.wait_for('message') waits until any message is received (including from your own bot which is probably what's happening there), not necessarily one in the current channel/from the command author; you should use the check= argument to filter your events
(oops robin answered as well)
okie
yes, you are not forced to stick to that confirmation view template
Oohh
I didn't knew that
Thanks!
a generic confirm view is more useful if you find it really common to ask the user for confirmation in your commands
Anyone know what could cause this?
usually caused by excessive blocking code
I receive an error when trying to use the interaction.delete_original_response()
ERROR - discord.ui.view : Ignoring exception in view <ConfirmationButtonView timeout=None children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Confirm' emoji=None row=None> Traceback (most recent call last): File "/home/codespace/.python/current/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task await item.callback(interaction) File "/workspaces/AdeptusTeam-PyBot/cogs/newProject_Cog.py", line 15, in confirm await interaction.delete_original_response() File "/home/codespace/.python/current/lib/python3.10/site-packages/discord/interactions.py", line 524, in delete_original_response await adapter.delete_original_interaction_response( File "/home/codespace/.python/current/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: 10015): Unknown Webhook
you didnt use it on the button's own interaction right?
yeah
@discord.ui.button(label = "Confirm", style = discord.ButtonStyle.green)
async def confirm(self,interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.delete_original_response()
#await interaction.response.send_message(f"Project is being created")
self.value = True
self.stop()
once you respond to an interaction you can delete its response, so if you want to delete the command's response you need the command's interaction
in there you only have the button's interaction
So, what if I use the self.value to check which button was pressed and then respond
sure if you prefer that approach
pass the command's interaction as an argument to the view's __init__, then reference it in the confirm/deny callback
normal object oriented programming stuff
It worked better than I expected
Thanks man!
😄
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
Oh ok, thanks
is there some problem with discord-py-slash-command library
always show this announcement although i tried to downgrade and upgrade
.
!rule 9
Just post it here
If it takes 300 messages and it's Discord related you're allowed to post it here.
Large portion including myself don't want to take things to DM.
:/home/container$ if [[ -d .git ]] && [[ ${AUTO_UPDATE} == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python ${PY_START_FLAGS} /home/container/${BOT_PY_FILE}
/usr/local/bin/python: can't open file '/home/container/bot.py': [Errno 2] No such file or directory
any one know to fix this
?
if i want a task to start when a cog is loaded, do i put the task in the class or above it?
what
i have a task loop, right now in the cog class but for some reason its not getting starting, so im asknig if i have it in the wrong place
ohhhh i should probaly put this in the main......
in cog_load method of the cog
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
override it
ahhhh thank you!!!
you can put in a cog
you need to start it
@task.loop()
async def mytask()
pass
mytask.start()
you need to start your task best way in a cog is to put mytask.start() in __init__() function
the mentioned directory does not exists
hell yea thank you!! it worked!
You haven’t set a call back for it
can you give like an example
no
any docs or git?
You shouldn’t need an example for this
!d discord.ui.Select.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
It’s an attribute. You set the value to your callback
so i put it in the on_select function?
All these work arounds can just be avoided by using the select decorator
!d discord.ui.select
@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, default_values=..., row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
i used the decorator but it didnt work for some reason
oh its small select
i used the big select as decorator
dudw
one more question how do i start a Modal
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
how to fix pip erro 🙂
show error
iscord.ui.view Ignoring exception in view <EmbedBuilderView timeout=None children=3> for item <Select placeholder='Select to Edit The Embed' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Title/Description' value='title/description' description='Change the title and description of the embed!' emoji=None default=False>, <SelectOption label='Footer' value='footer' description='Change the footer of the embed!' emoji=None default=False>, <SelectOption label='Author' value='author' description='Change the author of the embed!' emoji=None default=False>, <SelectOption label='Image' value='image' description='Change the image of the embed!' emoji=None default=False>, <SelectOption label='Thumbnail' value='thumbnail' description='Change the thumbnail of the embed!' emoji=None default=False>, <SelectOption label='Add Field' value='addfield' description='Add a field to the embed!' emoji=None default=False>, <SelectOption label='Remove Field' value='removefield' description='Remove a field from the embed!' emoji=None default=False>]>
Traceback (most recent call last):
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "d:\Projects\Python\FeXoBot\handlers\views.py", line 548, in on_select
await InteractionResponse.send_modal(interaction, TitleDescription)
File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 963, in send_modal
if self._response_type:
^^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute '_response_type'
``` Got this
What’s the error?
this
idk ithink nobady can help me
Share the error
Python 3.12.1
:/home/container$ if [[ -d .git ]] && [[ ${AUTO_UPDATE} == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python ${PY_START_FLAGS} /home/container/${BOT_PY_FILE}
trying to start
but not starting
this aint the error
anyone know to fix this >_<
That’s not an error
whttt its not errror
but icant start the server
Take a screenshot of your terminal
do you have bot.run(TOKEN) or client.run(TOKEN) in your code
file dont exists
is this solarhosting?
bot.run
The directory you’re trying to access doesn’t exist
how to do that
if this is solarhosting you need to go into the settings and select the file you want to run instead of bot.py
Here in Startup put the name of your main file here
ha'
got this error
thankz its working
🙂
err you shouldnt be using the InteractionResponse class directly
normally you reference it from an existing interaction, i.e. interaction.response.send_modal(MyModal(...))
oh
is there a way to add Options in Modal like a True/False
no
well
unless you're fine with having the user type in that option, not really
i know select menus used to be unofficially supported in modals ( #discord-bots message ), but since then it got removed and they never finished it
Hello
@commands.hybrid_command(name = "mute", description = "Mute a member")
@commands.has_permissions(mute_members=True)
@commands.guild_only()
async def mute_user(self, ctx: commands.Context, member: discord.Member, seconds: int = 0, minutes: int = 0, hours: int = 0, days: int = 0, reason: str = None):
if member == ctx.author:
await ctx.send("You can't mute yourself")
return
if member == ctx.guild.owner:
await ctx.send("You can't mute the owner")
return
if member.guild_permissions.administrator:
await ctx.send("You can't mute an administrator")
return
if member.top_role >= ctx.guild.me.top_role:
await ctx.send("You can't mute a member with a role higher than me")
return
if member.top_role >= ctx.author.top_role:
await ctx.send("You can't mute a member with a role higher than you")
return
if seconds == 0 and minutes == 0 and hours == 0 and days == 0:
await ctx.send("Please specify a time to mute")
return
duration = datetime.timedelta(seconds = seconds, minutes = minutes, hours = hours, days = days)
await member.timeout(duration = duration, reason = reason)
embed = discord.Embed(description = f"{member.mention} has been muted for {duration}", color = discord.Color.dark_purple())
embed.set_author(name=f"{member.name} has been muted", icon_url=member.avatar)
await ctx.send(embed=embed)```
I got error "You are missing Mute Members permission(s) to run this command."
but the permission is ok
mute_members isn’t a valid permission
why have soo many time mesurements
just use like hours
Because you can mute only 30 secondes or mute 7 days
just use minutes than
I don't think you want to calculate everythimes how many hours for 30 days
make a custom convertor
you can use a converter to convert them into days hour min and stuff
make it a string
like !mute @kazimabbas 20d
and make a converter to convert it
yes i know i need to make that, but before i want to fix the error
This is the first version of this command
just use the manage_members permission
Traceback (most recent call last):
File "/home/container/main.py", line 9, in <module>
from cogs.moderation import ModerationCog
File "/home/container/cogs/moderation.py", line 5, in <module>
class ModerationCog(commands.Cog):
File "/home/container/cogs/moderation.py", line 96, in ModerationCog
@commands.has_permissions(manage_members=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 2200, in has_permissions
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
TypeError: Invalid permission(s): manage_members```
can yo show the cod
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
this code just with the manage_members
its not manage_members but moderate_members
you can add an if statement like
if not ctx.author.guild_permission.mute_members:
await ctx.reply("YOU DONT HAVE PERMS")
return
well try moderate
download link for what ?
I mean.. if you can't download Python in the first place, making a discord bot is probably not the best idea as a beginner project, it's made for people with advanced knowledge with the language itself
i have really start to learn python with discord bot 3 years ago
It's literally in the middle of your screen after searching for "python" and clicking the first link..
Will likely be a fun experience when you will face errors :)
okay so, how do i get advertisement for my bot?
i want to start earning money with my RP-Utilities bot
Just use ctx.typing
that's equivalent but sure
i personally like hikari the best
It's personal preference
pretty sure nextcord is better for slash commands
and what would discord.py be better for ?
also may I know why ?
More faster and lightweight, has a lot more command handlers to choose from, and gives you more control over the bot imo
It’s powerful unlike dpy since that is extremely beginner friendly
Can you give some examples of command handlers hikari has?
hikari-lightbulb, hikari-tanjun, hikari-crescent, (very new) hikari-arc
and how is that a benefit?
You have a variety to choose from, but how is that actually beneficial for the end user?
depends on the user but they can choose based on their preferred coding style and which one they like more
imo, i use hikari-lightbulb and i found that to be the easiest to switch from dpy to hikari, but each user can have a different preference
so you're saying that hikari is kinda more professional?
since as u r saying
u say that dpy is more beginner friendly
yes
so like what's more professional about hikari
like I do got pretty good experience in python
both libs are hard to use if you're just starting out with python
2 years of python so I don't care if it's beginner friendly or not but I want the thing that is more professional and will make better bot using it
whether hikari is more "professional" than dpy depends on the specific needs and preferences of the developer
hikari is modern and asynchronous with high-performance. dpy is also async and might be considered more "pythonic" and follows the principles of the discord api closely, its also very easy to use and understand
hikari has a smaller community but the devs are active and respond. the docs might be hard to comprehend for a new user, but youll get the hang of it. obviously, dpy is way larger and has easier docs
hikari is more flexible, you get more control over your bot and you can again choose a command handler that you prefer. dpy is less modular than hikari and might be seen as simpler for other developers
I'm mostly planning to make a public bot to be honest such as probot etc so like I want it to be professional with a big database it will be mostly for moderation plus things like (ticket system, level system, economy system) so yeah I want to make sure that what I'm going with will be able to give me a good results for a public bot
a lot of people have big bots with hikari
Hi
but it depends on your specific needs of your bot, but i would recommend hikari over anything else
how execly do u get paid from discord bots(if you own them)
Discord doesn't pay you ,you have add some premium features and earn from it maybe?
I will definitely check it out thanks
alr, ty
So really all you get is to choose the command structure
discord.py has had a 7 year lifespan, and covers the entirety of the API
It’s very difficult and rarely done. All you can do is create premium features or commands. Discord bots have a terrible ROI so you shouldn’t expect to make your money back
to do a countdown timer, do i just update the message with the correct time left or is there is like a built timer function or anything
You’re going to get ratelimited instantly
If that lib floats your boat
There’s just no objective reason on why hikari is better than discord.py
phrasing it as such is misleading
exactly my issue, so how should i go about doing that?
If that’s what you think
Provide an objective reason then lol
I also never stated anything about hikari being better than dpy lol
I stated some pros about hikari and why one would switch from dpy to hikari
“It’s powerful unlike dpy since that is extremely beginner friendly”
Nothing you can do. Rethink the timer I guess. You can use discord timestamps instead
Not gonna argue with someone who’s chronically online
I’m not pressed, im just challenging your position
You made an objective statement and are refusing to back it up
how do countdown bots work then? they show a countdown, like dyno, is it the embed the issue?
No I just don’t want to argue with someone who’s chronically online. I stated the pros about hikari and why one would switch over, suggesting to the person who wants a new lib to learn and see if they want to go with hikari and you can’t seem to handle that
No, you said hikari is more powerful than discord.py and listed a choice of command handler as your only reason
dunno what countdown you’re referring to
You’ll have to show an example
can you show us what you mean
based
yea of course, how can i show what a bot does? want me to invite you to my server to see dyno?
send a screenshot
ahh gotcha
Also keep in mind basing your features on large bots implementations isn’t a good idea as they have access to more lenient rate limits
👍
😹
it does it for the last minute. up until the it says like 57 minutes left, etc..
yeah that's a discord timestamp
Yup, those are discord timestamps
oh ok... thanks, ill go learn about discord timestamps hahah
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
I have a gist for you
here's a utility method to make it
One moment
make sure the style is "R"
Is it possible to have a command be both slash and text?
for example:
/reply
!reply
yes, they're called hybrid commands
but they're a bit more complex and have limitations so just be wary of that
What are the limitations?
oh ok, im already usong datetime to figure out the end time
Which library are you using?
text command parsing is a lot richer than slash commands, but like in many systems the chain is as weak as the weakest link, so your text commands are significantly nerfed so they're compatible with their slash command counterparts
Main one i can think of is autocomplete and choices
ie no more greedy parsing or any sort of dynamic parsing. most of your converters are out too
They’ve severely limited with hybrid commands
so this would replace my format function i already have?
Fortunately I dont need them.
can you show us the format function that you already have?
greedy do work, but they are just a single argument instead when converted to slash
there's a list of some things that aren't supported in the docs:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#hybrid-commands
basically no nested group commands, variadic arguments, or union types, but both @app_commands.* and @commands.* decorators can be applied at the same time
wait wait wait. nested group commands?!
Why not just convert it to epoch time (it's epoch right?) and juse use this https://gist.github.com/LeviSnoot/d9147767abeef2f770e9ddcd91eb85aa
yeah probably
day 12 of coding python bro....... thats why hahah. i figured i wasnt doing it the most efficient way but it was working lol
Would the parent command of a hybrid group have the ability to only be invoked via prefix, or is it disabled outright for the sake of the library
oh dang. well. goodjob then. ur already as good as me ;D
hahaha
and I've been straggling along here ignoring the advice of the pros for over 2 years now
Do as I don't and you'll be a pro in no time
Follow the pepp8 standards.
a fallback= argument can be specified in the hybrid_group() decorator which defines the subcommand name that it'll map to
ah
ok so ill just replace my current countdown stuff with epoch in the field and it will update according to the the format i choose? which would be relative time?
if you do epoch time and use discords built in time converters, it'll change the format to your local time
So you dont need to worry about it being in the correct time format for everybody
it'll just translate it for you.
For example, if i convert my current machine time to epoch and use the discords time formatting, you might see it as 30/12/2023 whereas for me it's 31/12/2023 right now
#Australian
it might even put it as 12/30/2023
idk, i'm not american.
does that matter if its just countng down a duration? im already converting it to the um... i forget the name. the seconds since 1970 or something and thats how im saving in the database for end time or id have to change that to?
i havent seen first-hand the restrictions on hybrid groups, but if you look at what's supported in the discord api docs, discord.py hybrid commands might only support the very first example shown there based on the prior link
actually source code seems to line up with this limitation too:
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ext/commands/hybrid.py#L774-L775
Are u posting the time to discord?
im not displaying the time, i want to display how much time until a specified duration is over. im doing a giveaway just dyno
and want to do a countown timer like dyno
<t:1703997900:R>
Oh then whatever you're doing is fine. disregard what I'm saying. I thought you were posting it to discord for all to see.
@timber lotus This is an example of what you’re looking for
i wanted a 00:00 but since thats not possible, ill settle for whatever is haha so yes
Win some you lose some
Yep
haha exactly
If I was going to do a giveaway bot, I'd get a bit lazy.
I'd set up one of those looping thingies discordpy provides, have it check every minute once started (It starts off..)
When I do /giveaway X time, it will post an embed to the channel, turn loopy on, store time in database. if time.now() is equal to or greater than stored db time. the giveaway ends \o/
I'll look into it. The command only has 1 input anyway.
/reply Whatever you want to say
and
!reply whatever you want to say
Basically it's so people can reply to the support ticket.
I just want a hybrid command coz most support bots use !m to reply and I want to capitalize on that nonsense by also having !m 😄
yea i already have code for ending the giveaway, a check loop. it starts when the cogs loads but stops if returns no giveaways with current_time that hasnt passed the end time, has started and winner is null in teh database. the it gets called when the start button is pressed. i had the update countdown timer seperate, so i should put this in with the checks? im already saving the message_id, i assume i need that for it? or should i put this in my embed?
you can skip all of that because you can just sleep until a given time
no need to loop every minute, it's inaccurate
O:
discordpy has sleep?! or were you thinking asyncio.sleep?
or are both the same?
wait, bots need people to reply to a ticket with a command? seems a bit over complicated
i was trying to use asyncio sleep to update the message
but kept getting rate limited and got me thinking i wasnt doing it efficiently
subtract the target datetime from the current time, get seconds, pass into sleep
No. The ticket itself uses a command.
So to open a ticket, you DM a bot. answer all the fun questions.
A channel is made, you as the general user, cant see the ticket, but staff can. inside the ticket is private sensitive stuff the staff needs to address the ticket etc. but they can also discuss the issue.
The staff can then use a command to reply to the ticket (send a message to the user)
and if the user wants to reply, they dm the bot.
it's not my favorite way of doing a support ticket bot, but it's what the community likes/wants so it's what I'm catering to
sounds a lot like @novel apex
basically
so can i use any of this? or start over
But i need modifications to it
it's source code could serve as inspiration to you, perhaps
or you can modify it directly like we've done
you don't need any of that
Discord handles updating the time remaining on its own client side
note that string parameters for slash commands don't support newlines, so if that's important you'd probably have to make a separate slash command that pops up a modal for them to type their text (though this trades off markdown preview/autocompletion cause thanks discord)
nice.... so i guess put that in the embed and discord will do the work for me?
yes
well slash commands dont really work on mobile anyway.
ah, ive never used a ticket system like that
Also. as long as ur typing within the param field box, it doesnt matter.
thank you bro! i really appreciate the help. thank you everyone
No worries
see 😄
how about using a message context menu to trigger a reply? they send their message as normal and then right click > apps > reply to ticket
imo it's still a worse experience than the prefix command, but better than a slash command
I could just have the bot delete their original message, resend it, and attach buttons..
if the original author clicks the button it sends.
alternatively pinging the bot as a prefix might be a reasonable solution, particularly if you were making a ticket bot that couldn't use the message content intent
hhmm
do all of them at once and see what your users prefer 
based
File "/home/container/main.py", line 567, in <module>
bot.run(token, bot=False)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 723, in run
return future.result()
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'strip'
anyone know this server not starting
self bots are not allowed by discord's terms of service
ohh
!paste @slate swan you can paste your error message here
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.
Ignoring exception in view <DropdownView timeout=None children=1> for item <Program placeholder='Choose a Program...' min_values=1 max_values=1 options=[<SelectOption label='IGCSE' value='IGCSE' description=None emoji=None default=False>, <SelectOption label='AS and A Level' value='AS and A Level' description=None emoji=None default=False>] disabled=False>:
Traceback (most recent call last):
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Kaushik\Documents\Programming\r-IGCSEBot Code\r-IGCSE-Beta\resources.py", line 136, in callback
await interaction.response.edit_message(view = view)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 1063, in edit_message
payload["components"] = view.to_components()
AttributeError: 'IGCSE' object has no attribute 'to_components'```
what is this error?
i am coding a dropdown list that works smth like this:
the user runs the /resources command
it shows the dropdown list with two options (IGCSE & ALEVEL)
when the user selects an option
it shows the subject group (Science, Mathematics , English and more)
when the user selects an option, it should edit the message to shows the subject links to a website
the multidict dependency has no pre-built wheels for python 3.12 so pip is asking you to install c++ build tools in order to compile it
to fix it you can either downgrade to python 3.11 (easiest solution), or follow its recommendation to compile the package if you want to keep python 3.12
apparently IGCSE isn't a subclass of View, which is what you need in order to use the view= parameter
in your case you can either put your ICGSE select class inside a view: py view = discord.ui.View(...) view.add_item(ICGSE()) or rewrite it as a view subclass using discord.py's decorator syntax, which you might find easier to read: ```py
class ICGSE(discord.ui.View):
@discord.ui.select(options=...)
async def subject_group(self, interaction: discord.Interaction, select: discord.ui.Select):
... # works the same as callback()
view = ICGSE()```
huh i don't get it
so in discord.py, you can only send message components (buttons and select menus) by putting them inside a "view", an object that contains all the components for a message
yea
right now you've basically written await interaction.response.send_message(view=ICGSE()) which discord.py doesn't support because your ICGSE class inherits discord.ui.Select, not View
yes....
so you need to either put your ICGSE select inside a view object which you can give to send_message(), or you can turn ICGSE into a view subclass where the select menu is already defined in the class, and then give that to send_message()
oh wait you're using nextcord, in which case the second example should have (self, select, interaction) for the callback parameters (docs)
fyi you've already been doing the first approach in your code, for example in the IGCSE callback you create a view and add your various buttons to it: py view = discord.ui.View(timeout=None) for subject in subreddits[group].keys(): view.add_item( discord.ui.Button(label=subject, ...)) await interaction.response.edit_message(view=view)
import json
from discord import app_commands
from config import TOKEN
from discord.ext import commands
intents = discord.Intents.default()
intents.commands = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
with open("config.json", "r+") as f:
config = json.load(f)
TOKEN = config["TOKEN"]
@bot.event
async def on_ready():
print("bot is online")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
@bot.tree.command(name="test", description="just a test")
async def your_command(ctx):
if discord.utils.get(ctx.author.roles, name="Whitelisted"):
await ctx.send("Command executed successfully!")
else:
await ctx.send("You do not have the required role to execute this command.")
bot.run(TOKEN)```
why is this happening?
helo
iam intsalled pip but no show anythink
anyone know this issue ?
:/home/container$ if [[ -d .git ]] && [[ ${AUTO_UPDATE} == "1" ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python ${PY_START_FLAGS} /home/container/${BOT_PY_FILE}
Traceback (most recent call last):
File "/home/container/main.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
in cmd console, do pip install discord
same for you @hardy geyser
nothing changes
also says this for discord.py i need help installing if anyone can help me
are you using python 3.12?
^ assuming it's an issue with compilation, you should either downgrade python to 3.11 or install the build tools which should have been linked somewhere after that half of the error message
Someone help me please
literally read one message above

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
You'll have to search on your own
thats not violating terms of service tho im just getting usernams
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())
@bot.event
async def on_ready():
print('Ready')
@bot.command()
async def ping(ctx):
latency = round(bot.latency * 1000)
await ctx.send(f'Latency: {latency}ms')
bot.run('MTE5MD')```
No matter what i do i keep getting the same reponse:
```WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.```
Yes it logs in and stuff but it wont work the commands and i already have all the intents so i dont understand
do you have intents enabled on discord developer portal?
Intents.default() does not include privileged
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot is online")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} commands")
except Exception as e:
print(e)
@bot.tree.command(name="whitelist", description="Whitelist a user!")
@app_commands.has_permissions(administrator=True)
async def whitelist(interaction: discord.Interaction, ctx: commands.Context, member: discord.Member):
role_name = 'Whitelisted'
role = discord.utils.get(ctx.guild.roles, name=role_name)
if not role:
await ctx.send(f"Error: The role '{role_name}' does not exist.")
return
await member.add_roles(role)
await interaction.response.send_message(f"{member.mention} has been given the '{role_name}' role.")
line 22, in <module>
@app_commands.has_permissions(administrator=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.app_commands' has no attribute 'has_permissions'. Did you mean: 'default_permissions'?
the error
it's in app_commands.checks but you should use default_permissions as the error says
@bot.tree.command(name="whitelist", description="Whitelist a user!")
@app_commands.default_permissions
async def whitelist(interaction: discord.Interaction, ctx: commands.Context, member: discord.Member):
role_name = 'Whitelisted'
role = discord.utils.get(ctx.guild.roles, name=role_name)
if not role:
await ctx.send(f"Error: The role '{role_name}' does not exist.")
return
await member.add_roles(role)
await interaction.response.send_message(f"{member.mention} has been given the '{role_name}' role.")
still get an error tho
well you have to specify the permissions
line 22, in <module>
@app_commands.default_permissions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: default_permissions() takes 0 positional arguments but 1 was given
.
@bot.tree.command(name="whitelist", description="Whitelist a user!")
@app_commands.default_permissions(default_permission=True)
async def whitelist(interaction: discord.Interaction, ctx: commands.Context, member: discord.Member):
role_name = 'Whitelisted'
role = discord.utils.get(ctx.guild.roles, name=role_name)
if not role:
await ctx.send(f"Error: The role '{role_name}' does not exist.")
return
await member.add_roles(role)
await interaction.response.send_message(f"{member.mention} has been given the '{role_name}' role.")
says its not valid permission name what would i set it too
same as before
.
line 887, in decorator
command = Command(
^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 666, in init
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.globals)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 374, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\transformers.py", line 834, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\RHG\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\transformers.py", line 793, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.ext.commands.context.Context'>
PS C:\Users\RHG\Documents\Roblox Premium Scraper>
more errors /:
you can't have command context in a slash command
not here
can you priny event, birth and death and see what shows in the console
event not events, events is not defined
also, use the command then show me the console
i am in a big problem idk what to do
class RemoveFields(View):
def __init__(self, message:Message):
super().__init__(timeout=None)
self.value = None
self.message = message
self.embed = message.embeds[0]
self.fields = self.embed.fields
self.options = []
for i in range(len(self.fields)):
self.options.append(SelectOption(label=self.fields[i].name, value=str(i)))
@select(custom_id="remove_field", options=self.options, placeholder="Select a Field to Remove", min_values=1, max_values=1)
async def on_select(self, interaction:Interaction, select:Select):
selected = select.values[0]
self.embed.remove_field(int(selected))
await self.message.edit(embed=self.embed)
await interaction.response.send_message(
embed=Embed(
title="Field Removed!",
description="The field has been removed!",
color=Color.green(),
),
ephemeral=True,
)```
i cant use self in here
how do i get the options
hello any help, the bot doesnt send the "hello" ```import discord
from discord.ext import commands
import json
import logging
logging.basicConfig(level=logging.INFO)
with open('config.json', 'r') as config_file:
config = json.load(config_file)
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix=config['prefix'], intents=intents, debug_log=True)
@bot.event
async def on_ready():
logging.info(f'{bot.user} has connected to discord')
@bot.event
async def on_message(ctx):
logging.info(f'Received message: {ctx.content} from {ctx.author} in {ctx.channel}.')
await bot.process_commands(ctx)
@bot.command(name='hello')
async def hello(ctx):
await ctx.send('Hello!')
bot.run(config['token'])```
@bot.command()
async def hello(ctx):
await ctx.send('Helloooo')```
!mcintent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
how do i set sizes for buttons under an embed? i only have 2 so i want them to sit side by side and equal size. right now more letters = bigger button and not always side by side
There's no way to explicitly configure button size, however you might be able to do that with whitespace chars
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
The last two line is obsolete, read what docs on Intents.default() say
actually if he wants to disable typing its correct way
how to use cmd without prefix
set prefix to empty string
or if you want to use either with or without prefix
set prefix to tuple like this ("!", "") also i belive you have to put empty string last
other wise every prefix after it wouldnt work
or maybe not actually
doesnt matter rn
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.
its explained in the note
thankz @slate swan 🙂
i just so Intents.all() cause i am lazy to configure all intents manually
@app_commands.guild_only()
class Alliance(app_commands.Group):
alliance_group = app_commands.Group(name="alliance", description="Allows you to manage your alliance")
@alliance_group.command(name="create", description="Creates a new alliance.")
@alliance_group.command(name="add_player", description="Adds a player to the alliance.")
bot.tree.add_command(Alliance(name="Alliance"))
Can someone please assist, I want to make a group called alliances that has commands add_player and create. But right now the command comes up as /alliance alliance add_player
it should be
@app_command.Group(name="")
async def alliances(self, interaction)
ok how do I make the subcommands then?
i dont really know about the app_command if its diffrent but for hybrid commands it just
class Commands(Cog):
@commands.hybridcommand_group(name="")
async def afk
@afk.command()
async def list
can anyone help? I have no idea how i will do this:
my plan is to allow people to create macros that are string commands created to the bot, for exaple:
##attack
it will roll 1d20 since inside ##attack there is the command:
!roll 1d20
being the ! the thing that will decide the command, if you want math it would be like
!math 2+2
and that would be inside a command with double # at the beggining, for example i can call it ##simplemath
my sintax to create the command is, having an input for command name and an input for the command string, for example:
/macro create ##attack "!roll (1d20+5)"
and i'm also planning to add if and else case, example:
/macro create ##attack "!echo (sucess) !if (!roll 1d20 > 10) !else (!echo (failure))"
so the bot will first make the roll to confirm if the randomizer got higher than 10 in roll 1d20, in failure it will output "failure", on sucess it will output "sucess"
like, it probably need some complex coding that i don't know
so i need someone experient to help me out on this
@commands.Cog.listener()
async def on_message(self, message):
checker = message.content
if not checker.startswith("##"):
return
``` this is useless this doesnt havea purpose if you dontplan on adding any
being honest i dont get what you are tring to do
it's to check if the message is a macro
where are you missing?
but you are justing returning anyway to whats the point of check
yeah, it's because i'm gonna use it later
ok then its k
like, if i already created ##attack for example
when i execute ##attack
it will roll 1d20 and return the result
the think i am understandign you are trying to do is you have user enter a string then you convert that string into there corresponding commands?
and run them accordingly
yes
you can prob use a dictionary to do so
uhmm, any examples?
wait a sec
!e
def attack():
print("I am attacking!")
def roll():
print("I am rolling!")
def jump():
print("I am jumping!")
def defend():
print("I am defending!")
methods = {
"attack": attack,
"roll": roll,
"jump": jump,
"defend": defend
}
message = "attack jump defend roll"
for word in message.split():
if word in methods:
methods[word]()
you can link the word to a function
and rolle them in order
@severe sonnet
you can make 1000s of commands and just use this
!e
def attack():
print("I am attacking!")
def roll():
print("I am rolling!")
def jump():
print("I am jumping!")
def defend():
print("I am defending!")
methods = {
"attack": attack,
"roll": roll,
"jump": jump,
"defend": defend
}
message = "attack defend roll jump"
for word in message.split():
if word in methods:
methods[word]()
@fiery girder :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | I am attacking!
002 | I am defending!
003 | I am rolling!
004 | I am jumping!
you can even change the order and it will execute according ly @severe sonnet
oh yeah, time ti implement
with?
i’ll tell you in dms
good luck
okay uhmm, how do i separate the contents of my string command?
i'm planning to either with !if and !else and without them
for example
!math (25+5) !if (!roll (1d20+5) > 15) !else (!math (-5+0))
so i want it to be separated like
["!if", ["!roll", "1d20+5", "> 5"],["!math", "25+5"], "!else", ["!math", "-5+0"]]
so the program will first make a check, then if true execute the 2 index, else it will return to else to execute the 4 index
or, to make it more organized
[["!if", ["!roll", "1d20+5", "> 5"],["!math", "25+5"]], ["!else", ["!math", "-5+0"]]]
now without if and else
!math 25+5
would be
["!math", "25+5"]
category = discord.utils.get(guild.categories, name=category_name)
``` How do I check to see is a category already exists?
category = await bot.get_guild(GUILD).get_channel(id=CATEGORYID or name=CATEGORYNAME)
you prob need to add some paces
Invalid syntax
if its like !math 2+2 !attack 5
you can just check which one of them returns a function and use the rest as the inputs
in get_guild
uhmm, example?
oh i get it
thought in this case i will need to use regex to separate
Awesome thank you
okay so, the problem here is to organize the input and command in such a way i can work it out better
!e
def math(a):
print(a + a)
def attack(int):
print(f"I am attacking {int}!")
def roll(str):
print(f"I am rolling {str}")
def jump(obj):
print(f"I am jumping to {obj}!")
def defend(opponent):
print(f"I am defending! against {opponent}")
methods = {
"attack": attack,
"roll": roll,
"jump": jump,
"defend": defend,
"math": math
}
message = "math 2 attack 5 defend mike jump wall"
method = None
for word in message.split():
if word in methods:
method = methods[word]
else:
method(word)```
cus using .split() gonna make it confuse to manage it
Hold on, this is for a channel, I need to look for a category
oh i see, though, since i'm using () to input i have no idea how i will organize
!e discord.CatergoryChannel
its a CatergoryChannel
!d discord.CategoryChannel
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the category’s hash.
str(x) Returns the category’s name.
let me see a thing
what thing
!e
cmdstr = "!math (2+5**2) !f (!roll (1d20) > 5) !else !math (5+2)"
cmdstr.split()
print(cmdstr)
@severe sonnet :white_check_mark: Your 3.12 eval job has completed with return code 0.
!math (2+5**2) !f (!roll (1d20) > 5) !else !math (5+2)
now you can take !math for one comand and the brackets as a input
!e
cmdstr = "!math (2+5**2) !f (!roll (1d20) > 5) !else !math (5+2)"
result = cmdstr.split()
print(result)
@severe sonnet :white_check_mark: Your 3.12 eval job has completed with return code 0.
['!math', '(2+5**2)', '!f', '(!roll', '(1d20)', '>', '5)', '!else', '!math', '(5+2)']
okay i'm starting to realize
you can easily remove ! from !math
yeah though i'm planning to use ! as a command definitor
it's to make it easier for macro programmers create their macros
like a signalizer
yea you can do that
hey guys, im making my suggestion system and its my first time working with Modals. can someone help me with this error please
!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.
sure i have worked with models befor
How are you sending the modal
Modals shouldn’t be added to views
from button
here
You never called super().init on the Modal subclass
i need to call it?
super().__init__()
class Footer(Modal):
def __init__(self, message:Message):
super().__init__(timeout=None, title="Footer Embed Builder", custom_id="footer")
self.message = message
self.value = None
text = TextInput(label="Text",placeholder="Enter Your Text", min_length=1, max_length=25, row=0, required=False)
icon_url = TextInput(placeholder="Enter The Icon URL", min_length=1, row=1, required=False, label="Icon URL")
async def on_submit(self, interaction: Interaction):
embed = self.message.embeds[0]
embed.set_footer(text=self.text.value, icon_url=self.icon_url.value)
await self.message.edit(embed=embed)
await interaction.response.send_message(
embed=Embed(
title="Footer Set!",
description="The footer has been set!",
color=Color.green(),
),
ephemeral=True,
)``` EXAMPLE
like this, right?
yes
im still getting this
Does this error occur when submitting it
yes
I want to code a discord command that uses roblox api to find users with premium does anyone know how i could do this
Is your discord.py version up to date
how can i check it?
pip show discord
huhh?
@final iron so i have a key system and i have the keys that are generated sent to a .txt in my files, I would want to create a command that can remove keys. Do you know how I could do this?
oh wait, i know, im using discord 2.3.2
import uuid
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
yourrole = 'Whitelisted'
file_path = 'keys.txt'
@bot.event
async def on_ready():
print("bot is online")
@bot.command()
@commands.has_permissions(administrator=True)
async def gen(ctx, amount):
key_amt = range(int(amount))
f = open("keys.txt", "a")
show_key = ''
for x in key_amt:
key = str(uuid.uuid4())
show_key += "\n" + key
f.write(key)
f.write("\n")
if len(str(show_key)) == 37:
show_key = show_key.replace('\n', '')
await ctx.send(f"Key: {show_key}")
return 0
if len(str(show_key)) > 37:
await ctx.send(f"Keys: {show_key}")
else:
await ctx.send("Somthings wrong")
@gen.error
async def gen_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}, you don't have the necessary permissions to run this command")
@bot.command()
async def redeem(ctx, key):
if len(key) == 36:
with open("used keys.txt") as f:
if key in f.read():
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Inputed key has already been used!")
await ctx.send(embed=em)
return 0
with open("keys.txt") as f:
if key in f.read():
role = discord.utils.get(ctx.guild.roles, name=yourrole)
await ctx.author.add_roles(role)
em = discord.Embed(color=0x008525)
em.add_field(name="Key Redeemed", value="Key has now been redeemed")
await ctx.send(embed=em)
f = open("used keys.txt", "w")
f.write(key)
f.write('\n')
else:
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Inputed key has already been used!")
await ctx.send(embed=em)
else:
em = discord.Embed(color=0xff0000)
em.add_field(name="Invalid Key", value="Inputed key has already been used!")
await ctx.send(embed=em)
@bot.command()
@commands.has_permissions(administrator=True)
async def clear(ctx):
try:
with open(file_path, 'w') as file:
file.write('')
await ctx.send(f"The content of {file_path} has been cleared.")
except Exception as e:
await ctx.send(f"An error occurred: {e}")
@clear.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention}, you don't have the necessary permissions to run this command")
@bot.event
async def on_message(message):
if "http://" in message.content or "discord.gg" in message.content:
if message.author.guild_permissions.manage_messages:
await bot.process_commands(message)
else:
await message.delete()
await message.channel.send(f"{message.author.mention}, you don't have permission to send HTTP links")```
commands wont work getting 0 errors
which command
try putting await bot.process_commands at the end of on_message event
outside of the if statements
Your gen command won't save the content to the file since you aren't closing the file
You could instead use with open (...) as f: if you don't want to handle the closing of the file
Everything
does while loops interfere with async def functions
which code should i replace for that
No, only using functions which are non async will block your code
@finite salmon
await log_msg.edit(embed=approve, view=self)
Pretty sure this is inside your modal's on_submit(), hence self is instance of Modal and not View
Yeah line 83 right here
Currently you will only execute commands if the message contains http:// or discord.gg and the user has the manage_messages permission
You probably want to check if the user doesn't have the manage messages permission and then delete the message and send your informational message.
And process_commands all the time, so outside of your if statement checking if http:// or discord.gg is in the message
Consider this gen code optimization
async def gen(ctx: commands.Context, amount: commands.Range[int, 1, None]): # notice the amount typehint
keys = [uuid.uuid4() for _ in range(amount)]
keys_txt = '\n'.join(keys)
await ctx.send(f"Key{'s' if len(keys) > 1 else ''}:\n{keys_txt}"
with open("keys.txt", "a") as f:
f.write(keys_txt + "\n")
с новым годом из России!!
How can I make my bot speak with Text to Speech in a discord message?
Happy 2024 comrade
@slate swan yay, do you know how to translate messages sent into the channel?
never made something like that unfortunately
but you would have to create a custom translator by
subclassing app_commands.Translator I guess
is there a way to make it so if a bot goes offline buttons still work when it comes back on?
buttons posted in an embed, for say, a giveaway haha
ahh i have to make the view persistant....
I'm trying to make a discord bot by subclassing from commands.Bot, but maaaaan I'm getting every error under the sun
initial version example:
from discord.ext import commands
from discord import Intents
from dotenv import load_dotenv
import os
class MyBot(commands.Bot):
def __init__(self, command_prefix, description, intents):
super().__init__(
command_prefix=command_prefix,
description=description,
intents=intents
)
async def on_ready(self):
print(f"Logged in as {self.user}!")
@commands.command()
async def hello(self, ctx):
await ctx.send("hello")
load_dotenv()
TOKEN = os.environ["BOT_TEST_TOKEN"]
bot = MyBot(
command_prefix="test/",
description="Test Bot",
intents=Intents.all()
)
bot.run(TOKEN)```
it runs, but as soon as I try to call the hello command (with `test/hello`) I can told hello doesn't exist as a command (`discord.ext.commands.errors.CommandNotFound: Command "hello" is not found`)
I then tried to manually register the command in __init__:
def __init__(self, command_prefix, description, intents):
super().__init__(
command_prefix=command_prefix,
description=description,
intents=intents
)
self.add_command(self.hello)```
I then get `discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: MyBot.hello() missing 1 required positional argument: 'ctx` when trying to use the command. but ctx is literally in the function definition?!
im new to python and discord but pretty sure you need intents bro
intents = discord.Intents.all()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="/", intents=intents)
I have intents
ahh yea i dont recognize that. i copied mine from the docs
Intents.all() is towards the bottom of the first block
it's weird because I never had issues with making bots by just defining functions
but I have had nothing but issues since trying to making a bot class
which makes me think I'm doing something wrong
and i had to use app_commands and then set the command up like this to get it into the slash command come up
@app_commands.command(name='channel-info',
description='Displays information about the channel or category'
)
async def channel_info(self,
interaction: discord.Interaction):```
hmm i'll try
from discord import app_commands
need that for app commands
or so i think. im new bro, im just saying what i had to do get the bot im working on to start getting the commands in the slash pop up
ah yeah I'm just getting an argument error
and no worries, I appreciate you trying to help tho
Hello everyone! How are yall?
Quick question:
Does any body know how to work with cogs and stuff? I've been trying to work with it all day long and no matter what I do I can't get it working. :/
😆
i can tell you what i had to do haha
but read above, im new and this is my first bot
🥲 Okay.
i have 8 cogs in my bot
from discord.ext import commands
from discord import Intents
from dotenv import load_dotenv
import os
load_dotenv()
TOKEN = os.environ["BOT_TEST_TOKEN"]
bot = commands.Bot(
command_prefix="test/",
description="Test Bot",
intents=Intents.all()
)
async def on_ready(self):
print(f"Logged in as {self.user}!")
@bot.command()
async def hello(ctx):
await ctx.send("hello")
bot.run(TOKEN)```
this works perfectly fine for me  but subclassing doesn't
oh man, cogs were another issue I had LOL
I kept getting async errors
haha i feel somewhat confident and createing and getting them to load
i told myself I would come back to this tomorrow instead, but it's just been bugging me so much lol
i swear my bot was working last week when I last worked on it
Well I got it to where it din't give erros but some reason it was not technically imported correctly and the command did not work. The console said command not found.
oh man. i'm having command not found as well
although my issue crops up even without cogs
like this
my code is literally exactly the same as everyone else's online, but my commands won't get added
(unless I'm missing something)
oh lol "doesn't exist as a command (discord.ext.commands.errors.CommandNotFound: Command "hello" is not found)" Thats exactly what it said to me.
Its alr. Ima keep trying 🥲
can you share your code
im not even sure what subclassing is bro hahah
oh it's just when you make a class and inherit from something else
eg in my top block of code where I do
class MyBot(commands.Bot):
...```
ohhh ok so i do that when i make a cog and then use stuff from that cog other places
oof i have 367 lines of code in my main file because I can't figure cogs out.
Can't get it
To import, I was using:
async def load_extensions(bot): for filename in os.listdir('./cogs'): if filename.endswith(".py"): bot.load_extension(f"cogs.{filename[:-3]}")
and others wich I removed.
ok well i didnt import mine that way, i added under the onready(), how about this, share 1 command that you would want in a cog
uh this one for example:
@bot.command(name="memes") async def memes(ctx: commands.Context): embed = discord.Embed( title="Error", description="This feature has been temporally removed by the bot Administrators.", color=discord.Color.red() ) await ctx.send(embed=embed)
I also tried like that by bot.load_extentions(cogs.cmds) but din't work.
!pastebin
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.
Will do so
using your info, thats how my bot does it and it works.
i messed up, it should be this to send it
await interaction.response.send_message(embed=embed)
Oh
It work- let me delete the cmds from the main file.
It doesn't for me. I must be doing something wrong.
use !pastebin and just share you whole code bro, 400 isnt alot haha
;-; k
did you see i messed and used the wrong interaction to send the embed?
YEa
is a whole mess I'm warning ya 🥲
!pastebin
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.
the link did?
A whole mess.. 🥲
im not used to bot commands haha ive only used the app_commands
Oh
when you tried my way, was the cog file in a folder named cogs?
Yes.
dont know why, but it has to be haha
is there a reason why your using ! as your command prefix?
But is the loading code correct?
i thought / was standard
A not really. Just simple to use yk.
ah gotcha
That is for slash commands
i was just curious.
No worries. 😄
and dont want slash commands? thats what i used lol
didnt know there were different ones hahah
😅 There are slash commands and text commands.
I think yea
ahhh oh yea i remember now
i wanted mine to show up in the discord pop up
let me see if i still have this webpage saved. it talked bot.load_extensions
Oh. Okay.
I'm pretty sure its the way I am loading it whats wrong.
`@bot.event
async def on_ready():
print('Bot is ready')
bot.activity = discord.activity.Game(name="! help")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)!")
except Exception as e:
print(e)
await bot.load_extension("cogs.Commands.py")
`
https://discordpy.readthedocs.io/en/latest/ext/commands/extensions.html
well your import is wrong at least, suppose to be from discord.ext import commands not from cogs. id start there
and dont think you have to "load" it if im understanding that page correctly... its news year eve,... been drinking and smoking haha
ahhh thats for the file not the main
0_____0 Okay.-
so yea probably have to load in the main a way..
Ima see if I can get that sorted out.
usually this group is popping hahaha kinda sad im your only resource jajaja
on the main should bot.add_command under on_ready
add_command is whatever the command name is
so it would me add_command(meme) for the one example you gabe
bot.add_command(meme)
🥲
Ohh
ohh Makes kinda sence
that will be the same as whatever you have under async def setup(bot) in the file. now this isnt cog, so dont think it needs to be in a folder
dont forget to import it the file into the main
btw, the code you provided is giving 13 errors is that ok?
Will do.
13 errors? haha um... probably not haha
Fixed it 😅
lol how???
It was not ordered correctly lol smh when I pasted it it din't paste the right way if that makes sence.
ahh the indents...
i dont know the different coding softwares but i use replit and their ai catches all of that
I feel I will give up, will have 1k+ lines of code 🥹
Really?
yea. its pretty great for simple stuff like that and it also generates code. great for beginers like myself because even if it dont work, it gives me a starting point or tells me which stuff to use, etc. and it hosts my bot. its cost money per month tho but not that much
haha bro i just finished a couple giveaway commands that was 480some lines. that was my 8th cog. its all about organization bro, make your code modular and its easier to trace errors and also when you want to change something
Oof.
Ima try this on replit see if it helps or something.
wish I could help