#discord-bots
1 messages · Page 216 of 1
!d discord.Role
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
Use this as a type hint
I don't understand
Apprentky it's not able to find role
At remove role but the role name is valid
wait a min lemme turn on my laptop
Okay
async def ...(ctx, role: discord.Role):
This is what he meant
What lib are you using
Whatever you pass on role args, it will be converted to Role object
1.7
What
You could try disnake instead
Lmao
Upgrade it
!pypi discord.py
I have 2.2
Lib name
2.2.0
Names and versions are different
Oh
is it pinned to 1.7
what does your toml file look like
doesn't that mean you are using v1 instead of v2
update that to say ^2.2.2 @hexed dagger
and do poetry install
Okay
Also I think I figured out where thr mistake is
It's not updating role_id1
To the correct arg1
That'd why it can't assign as role 0 is everyone
Oh I am fucking stupid
It's caused I break if one of them is found
Omfg kill me
It still doesn't work
It's not marching arg1 and role.name
Even though they are the same
does the role have a space
@bot.command()
async def coins(ctx , user: discord.Member):
embed = discord.Embed(title=user.name, description=":money_with_wings:", color=0x00ff00)
await ctx.send(embed=embed)
hey how to do like if there is no argument then show ctx.author.name
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
set a default argument like this ```py
async def coins(ctx, user: discord.Member | None = None):
if user is None:
user = ctx.author
async def coins(ctx, user: discord.Member = commands.Author):
``` works too
!d discord.ext.commands.parameter
discord.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=...)```
A way to assign custom metadata for a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")'s parameter.
New in version 2.0.
Examples
A custom default can be used to have late binding behaviour.
```py
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
await ctx.send(f'Hello {to.mention} :wave:')
This too works xd
discord/ext/commands/parameters.py lines 256 to 260
Author = parameter(
default=attrgetter('author'),
displayed_default='<you>',
converter=Union[Member, User],
)```
why would you redefine something that's already defined by the lib 
Idk 🗿
Code: https://paste.pythondiscord.com/zufahuhuhe
Issue: it's not processing two of them. only processing the first one...
it supposed to take a text from both of the variable..
and put both the text together
like this:
Text 1 = ABC
Text 2 = DEF
Im trying to make a ticket bot for my server. I wrote code that uses a /launch command that sends an embed with a button. When the button is pressed a channel is created and it will mention you in that channel if you try and press the button again it will not create a channel, and it does work but not the way it is supposed to. it create 3 channels at once and it creates 3 more when you press the button again.
Ticket Button Code:
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout = None)
@discord.ui.button(label = "Create a ticket", style = discord.ButtonStyle.blurple, custom_id = "ticket_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
ticket = utils.get(interaction.guild.text_channels, name = f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
if ticket is not None: await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}!", ephemeral=True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
}
channel = await interaction.guild.create_text_channel(name = f"ticket-for={interaction.user.name}-{interaction.user.discriminator}", overwrites=overwrites, reason = f"Ticket for {interaction.user}")
await channel.send(f"{interaction.user.mention} created a ticket!")
await interaction.response.send_message(f"Ive opened a ticket for you at {channel.mention}!", ephemeral=True)
Launch Command:
@tree.command(guild = discord.Object(id=no), name = 'launch', description='Launches the ticketing system')
async def launch(interaction: discord.Interaction):
embed = discord.Embed(title = "If you need support, click the button below and create a ticket!", color = discord.Color.red())
await interaction.channel.send(embed = embed, view = ticket_launcher())
await interaction.response.send_message("Ticketing system launched!", ephemeral=True)
I dont see any problem right there 🗿
see my problem instead
Send the full code
!pypi disnake
Difference of what
discord.py and disnake.py
ik thats why im trying to figure out why its not working 😭
like its working but not how its suppsoed to
i can send a recording of what it does
You probably have my instances of the bot running
??
Or multiple on_message listeners calling process commands
disnake is a fork of discord.py and they have different maintainers
their implementations of interactions and some other things are different
is the syntax the same
both are python packages and hence will follow python syntax
coz ima got a big bot i am lloking to migrate it for more slash commands
I mean do just have to do
import disnake as discord
dont
no
they both are 2 different libraries
if you already have discord.py code you might as well continue using discord.py
it also supports slash commands
if that's what your requirement is
i need normal and slash in same code
sure
but i dont thing it will work with discord.py
why?
idk it just doesnt work
doesn't work how?
are you getting an error?
it's best you always post your code and error if something isn't working
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
no it just doesnt know what to send
Actually I and my friend are working on a bot and he thinks he needs both types of command in one file and he asked his senior he said to use disnake
I mean if you already have discord.py code why would you move to disnake and waste time doing so much refactoring
^^ yep
he needs both / and normal commands in one bot
ok so I don't get what the issue is
what are you expecting from us exactly
it's absolutely possible to have slash commands and normal text commands with discord.py
you can use the hybrid command interface as suggested above, or make separate callbacks for both
how can you give me example
what actually is the point of cogs because it just seems like a more complicated way of commands
you can spread commands, events and loops into different files so its more organized
ok so its not like an essential thing but its better for cleaner code?
yeah i would say
Hello everyone, yesterday I spoke with a guy about embed constructors without cogs, and he said cogs is a great way to organize the bot. Can please anyone tell me about cogs?
they are often used with another feature called extensions (https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html)
in essence, a Cog is a subclass of discord.ext.commands.Cog that can be hot loaded
you can define commands and event handlers inside it, and hence use it to categorize your bot's features
https://paste.pythondiscord.com/qufawuxera
Issue: the bot is supposed to return values of the two variables (verses_list, verses_list1) but not returning the other variable's value (in the for loop inside the chapter function), rather, it is returning the first variable's value into the other variable's value place.
hey guys, this is part of my code for a giveaway bot that was working before but now it is not. its saying member is not defined here and im not sure what to define it as to get it working properly again. if i remember correctly the purpose was to see if the user is a part of the guild. so they have a user and a member account
userlist2 = [user async for user in newmsg.reactions[0].users() if isinstance(user, Member) and any(role.id in roleids for role in user.roles)]
!e
print(this_is_not_defined)
@shrewd fjord :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(this_is_not_defined)
004 | ^^^^^^^^^^^^^^^^^^^
005 | NameError: name 'this_is_not_defined' is not defined
!e
this_is_defined="Spook"
print(this_is_defined)
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
Spook
I think I fixed it. Defined Member as discord.Member
It will be discord.Member i am guessing
Oh nice
Thanks
Np
if response1.ok:
data = response.json()
I think it will be response1.json()
Should have checked the code again 💀
F
xd
fixed
Noice
discord.errors.NotFound:
To
discord.NotFound
!d discord.NotFound
exception discord.NotFound(response, message)```
Exception that’s raised for when status code 404 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
!d discord.errors.NotFound
exception discord.NotFound(response, message)```
Exception that’s raised for when status code 404 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
lol
what was the msg before u edited?
"Lop" average mobile users 🗿
Too fast to press send
if my bot tries to create many channels at once, how many channels can we create before getting rate limited?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Hi all - working on getting my bot command to spit out a random row from a MySQL database. Everything works on the backend, however, not seemingly getting the bot to communicate properly (no results returned). Have made great strides thanks to the helpful folks in this channel, but reached another impasse! When I replace the query variable with the string 'test,' it works no problem. Any suggestions on how to modify my code to achieve this would be most appreciated! Thanks in advance!
bot = interactions.Client(token=TOKEN)
loop = asyncio.get_event_loop()
@bot.command(
name="2kplayer",
description="Work in progress",
scope=GUILD_ID,
)
async def my_first_command(ctx: interactions.CommandContext):
conn = await aiomysql.connect(
host='127.0.0.1',
user='root',
password='root',
db='dominion_data',
loop = loop
)
cur = await conn.cursor()
await cur.execute('SELECT first_name, last_name, team_name FROM players_2k22 AS t1 JOIN (SELECT player_id as player_id_t2 FROM players_2k22 ORDER BY RAND() LIMIT 1) as t2 ON t1.player_id=t2.player_id_t2 LIMIT 1;')
query = await cur.fetchone()
# df = pd.read_sql(query, engine)
await ctx.send(query)
await cur.close()
conn.close()
bot.start();
Did u try Cursor.fetchall()?
let me give it a shot, thanks a ton for the reply
Also make sure to not forget to commit the database on the backend part, most people forget it 
oh don't i know it hahaha i work with data warehouse for my job, nightmares
xd
thanks for your time, will take a look at integrating this 🙂
Okay
Actually fetchone should have atleast return 1 record
Maybe it's the problem with executing query
yeah, i believe i tried fetchall, but want to try again to be sure
to be clear, everything works on the sql side and when i eliminate the bot from the equation it runs ok in python, meaning the row gets returned in the output randomly every time i execute
Also I dont think ; this matters anyway
Except for a sql file and u should quote the query with ""
essentially trying to refresh the query when the command triggers
yeah ; is my sql habit haha
Ohk
Also for more db help make sure to go on #databases and for a long and detailed help go create a forum on #1035199133436354600 👀
thanks! i do participate in the databases channel and was told to come here haha, essentially the database side seems fine, just working on converting data types atm and don't want to flood channels, and the help channel forum posts i post don't seem to get traction 😦
was encouraged to post questions here, is that cool still? has been a very helpful channel here
Yeah but actually experts more replies on the forum channel, so just make a channel there, you will get fast and useful reply
Or answer 🗿
perfect i'll make sure to get a post going there as well, and will still participate here, thanks for the guidance 🙂
Np
So my task.loop in my giveaway commnad does not loop it like i tried printing 1 and it printed only once.
on my vscode it works but in the hosting it doesnt.
No error either
@tasks.loop(seconds=5)
async def giveawayCheck(self):
async with self.bot.db.cursor() as cursor:
await cursor.execute("SELECT time, prize, message, channel, guild, participants, winners, finished FROM giveaways")
data = await cursor.fetchall()
if data:
for table in data:
time, prize, message, channel, guild, participants, winners, finished = table[0], table[1], table[2], table[3], table[4], table[5], table[6], table[7]
if not finished:
if pyTime.time() >= time:
guild = self.bot.get_guild(guild)
channel = guild.get_channel(channel)
if guild or channel is not None:
try:
participants = json.loads(table[5])
except:
participants = []
if not len(participants) == 0:
if len(participants) < winners:
winner = random.choices(participants, k=len(participants))
else:
winner = random.choices(participants, k=winners)
if winner is not None:
em = nextcord.Embed(title="Giveaway Results", description=f"{', '.join([guild.get_member(int(i)).mention for i in winner])} has won the giveaway for `{prize}` ")
await channel.send(f"{', '.join([guild.get_member(int(i)).mention for i in winner])}",embed=em)
await cursor.execute("UPDATE giveaways SET finished = ? WHERE guild = ? AND prize = ? AND message = ?", (True, guild.id, prize, message))
msg = await channel.fetch_message(message)
newEm = nextcord.Embed(title="Giveaway Ended", description=f"{', '.join([guild.get_member(int(i)).mention for i in winner])} has won `{prize}`   ", color=0x4b99bd)
newEm.set_footer(text=f"Enters - {len(participants)}")
await msg.edit(embed=newEm)
else:
await cursor.execute("UPDATE giveaways SET finished = ? WHERE guild = ? AND prize = ? AND message = ?", (True, guild.id, prize, message))
msg = await channel.fetch_message(message)
newEm = nextcord.Embed(title=f"{prize} Giveaway Ended", description=f"No one has joined the giveaway", color=0x4b99bd)
await msg.edit(embed=newEm)
em = nextcord.Embed(title=f"{prize} Giveaway Ended", description="No one has joined the giveaway", color=0x4b99bd)
await channel.send(embed=em)
await self.bot.db.commit()```
How do you start it?
The loop
@commands.Cog.listener()
async def on_ready(self):
await self.bot.wait_until_ready()
await asyncio.sleep(2)
print("Database Staus: Online")
self.giveawayCheck.start()
print("Giveaway Loop: Online")
I see
Hm..
Maybe it's taking time to return the data and again looping?
Can you add
print("started") on the top of loop
And print("ended") bottom of the loop?
yes
Try and check on the hosting
just printing started and not ended
So it's actually internal problem i assume in your loop
Maybe it's bot able to fetch datas from database thus blocking it
its weird
Maybe json.load doing weird stuff lol
OH WAIT
You have error handler bru
yep
okay
or fix your error handler which is probably the most important thing to do
Yep
idk whats the error
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
i got them already
first of all i dont see any intents there and second thing we cant help on projects that may break law
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
hi guys
i bought a vps and hosted my bot on it
and i want to know how to host it h24/7
could you help me ?
@cedar smelt can u help with sql ?
if your host have linux you can use nohup command to run it in the background like this: nohup python my_file.py > output.txt &
https://janakiev.com/blog/python-background/
can also read this tutorial
with it, the script will be executed h24 with my computer off ?
the vps must be on
not your pc
what do i have to put here ?
you can change name of the output file
rest leave it as it is
& means it runs in the background
okay
and > means to save all output to the file after
in this case named output.txt
oh
@slate swan uh ?
try without python
or instead of python try py, py3, python3
Great
hi I need help. I am about to have a stroke......
How can I make my python code copy "Dopey ean", "FAT AND FURI0U3", "iX latics" from this discord message
@slate swan @naive briar help me please 🤧
Me too lmao
regex probably
how do I do that
its working
you should use #❓|how-to-get-help
are u talking to me
@slate swan can u help?
if i knew how i would
yes
i made one already
when this command is there in the code, whenever i use a command, the bot does not reply or respond. but whenever i remove this code, it works. what might be the issue?
@bot.event
async def on_message(message):
if message.author.bot:
return # ignore messages from bots
channel = message.channel
channel_id = str(channel.id)
mycursor = db.cursor(buffered=True)
# check if the channel has the channel_type as "roleplay"
mycursor.execute("SELECT channel_type FROM channel WHERE channel_id = %s", (channel_id,))
result = mycursor.fetchone()
if not result or result[0] != "roleplay":
return # ignore non-roleplay channels
# check if the user has an ID in the users table
user_id = str(message.author.id)
mycursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
result = mycursor.fetchone()
if not result:
await channel.send("It is preferable that you use the -createid command before proceeding with the roleplay.")
return
# check if the user is on cooldown
if bot.user_cooldown.has_cooldown(user_id):
return
# calculate the payment amount based on the message length and characters used
message_content = message.content
payment = 10
if len(message_content) > 20:
payment += 5 * ((len(message_content) - 20) // 10)
if '"' in message_content:
payment += 10
if '*' in message_content:
payment += 20
# update the user's amount and apply the cooldown
mycursor.execute("UPDATE users SET amount = amount + %s WHERE id = %s", (payment, user_id))
db.commit()
bot.user_cooldown.update(user_id)
# process regular commands
await bot.process_commands(message)```
there are no errors either
but await bot.process_commands(message) is already there at the end
do you have any other on_messages
i changed it into a listener but still, to no avail:
@bot.listen('on_message')
async def roleplay_money(message):
if message.author.bot:
return # ignore messages from bots
channel = message.channel
channel_id = str(channel.id)
mycursor = db.cursor(buffered=True)
# check if the channel has the channel_type as "roleplay"
mycursor.execute("SELECT channel_type FROM channel WHERE channel_id = %s", (channel_id,))
result = mycursor.fetchone()
if not result or result[0] != "roleplay":
return # ignore non-roleplay channels
# check if the user has an ID in the users table
user_id = str(message.author.id)
mycursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
result = mycursor.fetchone()
if not result:
await channel.send("It is preferable that you use the -createid command before proceeding with the roleplay.")
return
# check if the user is on cooldown
if bot.user_cooldown.has_cooldown(user_id):
return
# calculate the payment amount based on the message length and characters used
message_content = message.content
payment = 10
if len(message_content) > 20:
payment += 5 * ((len(message_content) - 20) // 10)
if '"' in message_content:
payment += 10
if '*' in message_content:
payment += 20
# update the user's amount and apply the cooldown
mycursor.execute("UPDATE users SET amount = amount + %s WHERE id = %s", (payment, user_id))
db.commit()
bot.user_cooldown.update(user_id)```
i mean, hey at least this time the commands work
but this piece of code itself, eh does nothing
i just know to make a command you should do this
@Bot.command()
async def <command name>():
await <some code>
you don't have to await everything
only coroutines
i know
oh sorry i just forget that🤦♂️🤦♂️
no no im not making a command. i want the on_message listener to be there so that every time someone messages, values get added or removed from database.
i already found a fix but now the issue is that the main purpose of the command is not working at all
@bot.event
async def on_message(message):
#some code
this code is for getting new message
exactly what i did tho
You might run into performance issues down the line if you're making a database call for each message that gets sent
well, that's kind of true but i'm willing to make adjustments
Not really.
The amount of messages that have to get send would be incredibly high.
how do I add who made the changes in on_member_update?
like edited by who
how to custom colors with messages like that ?
test
you cant
all you can is make text green or red adding + or - before and using diff formatting like this:
+ green
- red
okay thanks
you can do way more than just that
check out this message #discord-bots message
show me 
hm good to know
bookmarked

@naive umbra i didn't really understand the message, could you just tell me how to make a message like that ?
test (in green) ・ test (in red)
tried it and doesnt look like it works now
\u001b[0;40m\u001b[1;32mThat's some cool formatted text right?
\u001b[1;40;32mThat's some cool formatted text right?
does not for me
The \u001b is the unicode for ESCAPE/ESC, see http://www.unicode-symbol.com/u/001B.html. If you want to use it yourself without bots, then you need to copy paste the character from the website.
Test
[0;30mTest
[0;31mTest
[0;32mTest
[0;33mTest
[0;34mTest
[0;35mTest
[0;36mTest
[0;37mTest
u have to copy the special character
put this before
screen shot and send the special caracter please
copy it from my message above
okok
```ansi
Test
[0;30mTest
[0;31mTest
[0;32mTest
[0;33mTest
[0;34mTest
[0;35mTest
[0;36mTest
[0;37mTest
```
Test
[0;30mTest
[0;31mTest
[0;32mTest
[0;33mTest
[0;34mTest
[0;35mTest
[0;36mTest
[0;37mTest
Hello, i'm wanting to store my own data instead of relying on an API (for various reasons). The data I want to store will be pokemon related data (pokemon data, region data, gym leaders, team rocket, items, moves and their effects, etc). What would be a good way to store my own data, I've heard that dictionaries and nested dictionaries created with the use of making instances of classes (like class Pokemon, class Abilities, class Types, etc).
I am new*ish to python, so could use a little nudge in the right direction (yes i know this is not quite a beginner friendly project, but never the less I intend to keep at it)
Storing the Pokemon data will be huge
You'll have to use an API
That's just more processing and more storage consumption
So how do i store data that i need stored that the API doesn't provide?
thank you, i appreciate it ❤️
from the little research i did, key word little so if you have any extra info to give that'd be great, but I need a multi processor and a lot of ram, well i have a multi core processor and i have 31 free GB of RAM, would that be enough just for the testing of my bot, once I plan on making the bot public, it will be converted to an actual hosting service
do bots need to be verified to do this?
i greatly appreciate the info
No.
oh
you mean the invite link or the fact that it is in-app?
if you send it inside a discord server it will be in-app
yea do i need a domain for it
oh u mean the "join servers for you" and "access username" part
yes
you need these two scopes
and you don't need a domain but you will need some kind of http server
Every single kb is precious 😳
just those?
not a domain but a web address yeah
oooh okay
so i know i have to host it w a local server or whatever but idk how to
https://yourdomainhere.com/discordauth
like that
i need heeelp
I'm using python to run a discord bot and i got a damn error that says ModuleNotFoundError: No module named discord_components'
i try to download the module by pip i do the py -m pip install discord_components
but it gives this error and there is no module such as discord-components
ERROR: No matching distribution found for discord-components```
dont use discord_components
use built in to discord.py components
i don't think that library has been updated since 2021
how can i do that do
i'm trying to run a py file and it says this
from discord_components import *
ModuleNotFoundError: No module named 'discord_components'```
don't bother with discord_components
you need to rewrite your code to use discord.ui classes
well
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
aight ty for the help
hi, how can my bot send a message to another channel? I use slash commands
you need to get channel object of channel you want to send message to
easiest way will be to use bot.get_channel(id)
then I use send_message?
yes you assign it to a varriable
and send
channel = bot.get_channel(12345)
await channel.send("...")
no
InteractionResponse.send_message only works in the current channel
okay, thank you !
you would just use channel.send
thank you
how to make dnd bot activity please ?
await bot.change_presence(status = discord.Status.dnd)
anyone know aioqlite?
Error binding parameter 3: type 'tuple' is not supported
try:
async with self.bot.db.cursor() as c:
await c.execute(f"SELECT * FROM customcommand1 WHERE user_id = ? AND trigger = ? AND message = ?", (ctx.author.id, trigger, message,))
check = await c.fetchone
if check is not None:
await c.execute("UPDATE customcommand1 SET user+id = ? AND trigger = ? AND message = ?", (ctx.author.id, trigger, message,))
await self.bot.db.commit()
elif check is None:
await c.execute("INSERT INTO customcommand1 VALUES (?, ?, ?)", (ctx.author.id, trigger, message,))
await self.bot.db.commit()
await success(ctx, f'Successfully **set** your message to **{message}** & trigger to **{trigger}**')
except Exception as e:
print(e)
await error_message(ctx, "There was an **error** proccessing this command. Check your message and try again")```
put an asterisk before the tuple
thats what i did
where is it in your code then
it works but its not updating the db
@smoky sinew
hey
i want to add footer to my embed please
await ctx.respond(embed = discord.Embed(title = "", description = f"", color = ))
@slate swan
what is this library
.set_footer is a method that does not return anything so you will have to use this
embed = discord.Embed(...)
embed.set_footer(...)
await ctx.reply(embed=embed)
you could do this though
class CustomEmbed(discord.Embed):
def set_footer(self, *args, **kwargs):
super().set_footer(*args, **kwargs)
return self
then you can use
await ctx.reply(embed=CustomEmbed(...).set_footer(...))
and for author ?
you can do the same thing
Is it possible someone can help me with my Discord bot that I host. Python using Ubuntu, had a bot Dev but he went MIA for months and really trying to finish something he started. Possible DM so itll be easier to communicate? Thanks
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for lavasnek_rs
Failed to build lavasnek_rs
ERROR: Could not build wheels for lavasnek_rs, which is required to install pyproject.toml-based projects
any1 able to help w this?
It says "cant find rust compiler" eventhough its installed
Can anyone help me with this
I have been trying to do something with numbers rn using isdigit() method to identify nums but i want to identify expression like additions and multiplications too, such as 4*5.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
why not just expression.isdigit() or any([operator in expression for operator in ("+", "-", "*", "/")])
of course there is probably an easier way
maybe use something like ast
thanks i achieved my goal using re this was a new to me i would learn more about this lib.
i guess that could work too
however i did have to use eval() function which bothers me if someone tried to mess with the code
What do I do now? Is there something that calculates only maths expressions?
Try safe eval
Does literal_eval() makes the same risk ?
!e ask the error
import ast
print(ast.literal_eval("1+1"))
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(ast.literal_eval("1+1"))
004 | ^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/usr/local/lib/python3.11/ast.py", line 110, in literal_eval
006 | return _convert(node_or_string)
007 | ^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/usr/local/lib/python3.11/ast.py", line 109, in _convert
009 | return _convert_signed_num(node)
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/ast.py", line 83, in _convert_signed_num
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/owawayicit.txt?noredirect
any1?
@dusty tree
lightbulb and hikari is the lib I use
yes what is your code
bot = lightbulb.BotApp(
TOKEN,
prefix=lightbulb.when_mentioned_or(PREFIX),
intents=INTENTS,
cache_settings=CACHE,
help_slash_command=True,
ignore_bots=True,
case_insensitive_prefix_commands=True,
logs={
"version": 1,
"incremental": True,
"loggers": {
"hikari": {"level": "INFO"},
"lightbulb": {"level": "INFO"},
},
},
)
what's the full code
import os
import aiohttp
import hikari
import lightbulb
import concurrent.futures
from random import choice
from utils.quotes import statuses
from lightbulb.ext import tasks
from utils.const import INTENTS, CACHE, TOKEN, PREFIX
bot = lightbulb.BotApp(
TOKEN,
prefix=lightbulb.when_mentioned_or(PREFIX),
intents=INTENTS,
cache_settings=CACHE,
help_slash_command=True,
ignore_bots=True,
case_insensitive_prefix_commands=True,
logs={
"version": 1,
"incremental": True,
"loggers": {
"hikari": {"level": "INFO"},
"lightbulb": {"level": "INFO"},
},
},
)
tasks.load(bot)
@bot.listen()
async def on_starting(event: hikari.StartingEvent) -> None:
bot.d.aio_session = aiohttp.ClientSession()
bot.d.process_pool = concurrent.futures.ProcessPoolExecutor()
@bot.listen()
async def on_stopping(event: hikari.StoppingEvent) -> None:
await bot.d.aio_session.close()
bot.d.process_pool.shutdown(wait=True)
bot.load_extensions_from("./extensions/", must_exist=True, recursive=True)
bot.load_extensions_from("./meta/", must_exist=True, recursive=True)
if __name__ == "__main__":
if os.name != "nt":
import uvloop
uvloop.install()
bot.run(
status=hikari.Status.ONLINE,
activity=hikari.Activity(
name=choice(statuses),
type=hikari.ActivityType.WATCHING)
)
i think token is positional, replace TOKEN with token=TOKEN
the token is getting pulled from my env file
show utils.const please
import os
import dotenv
import hikari
from hikari import Intents
from hikari.impl.config import CacheSettings
from hikari.api.config import CacheComponents
dotenv.load_dotenv()
#
# MAIN BOT RELATED
#
GUILDS = (
875986914367385600,
617173140476395542,
793239269723471902,
535677066138353674,
570976409452019722
)
PREFIX = [
"v!",
"V!"
]
INTENTS = (
Intents.GUILDS |
Intents.GUILD_MEMBERS |
Intents.GUILD_MESSAGES |
Intents.GUILD_VOICE_STATES |
Intents.MESSAGE_CONTENT
)
CACHE = CacheSettings(components=
CacheComponents.GUILDS |
CacheComponents.GUILD_CHANNELS |
CacheComponents.ME |
CacheComponents.MEMBERS |
CacheComponents.MESSAGES |
CacheComponents.ROLES |
CacheComponents.VOICE_STATES
)
TOKEN = os.getenv("BOT_TOKEN")
ight
well fixed main problem, the bbot goes live
I forgot I had added previous guilds I tested
does anyone know how i can show time like this where when you hover over it it shows info
!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 "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
so i would set up like this?
no
remove the style=None part, that's just part of the function signature
the style variable in this screenshot is set to R
where it says "2 days ago" etc
so set it to style=R? its giving me an undefined error
as a string
you can't just put a random letter in because python doesn't recognize it
How do I make the bot have like a custom rich presence like playing then blank blank
rich presence? or just presence?
Which ever one that shows the example I gave
!d discord.Game
class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity "discord.Activity") that represents a Discord game.
This is typically displayed via **Playing** on the official Discord client.
x == y Checks if two games are equal.
x != y Checks if two games are not equal.
hash(x) Returns the game’s hash.
str(x) Returns the game’s name.
await bot.change_presence(activity=discord.Game(...))
Dm me
why
is it possible to name commands with space in their name, im using pycord and it throws an error if i try to do so.
that looks like a subcommand
shift is a subcommand of work
oh ok im unaware of that concept
Is their any problem with multiple discord bot instances so long as they respond to different stuff?
I need some functions to be very responsive so they are on a vps
but I also have some functions that involve re-encoding and upscaling video which needs to run on my home server because I can't afford a GPU compute datacenter server and it's already too slow with a 3060ti.
so long as I only use the commands rewrite for one instance it should be fine right?
and use on-message for the other
How do I disable a button?
@discord.ui.button(label="Notes Previous", style=discord.ButtonStyle.red)
async def notes_previous(self, interaction: discord.Interaction, button: discord.ui.Button):
button.disabled = True
if self.pagenumber == 0:
self.pagenumber = len(self.notes) - 1
else:
self.pagenumber = self.pagenumber - 1
embed = self.setembed(self.pagenumber)
await interaction.response.edit_message(embed=embed, view=self)
``` This doesnt seem to work D:
I want to be able to disable it if there's no notes.
nvm figured it out ;D
Is it possible to put buttons on new rows? 🤔
Do you mean like reorder buttons? or put buttons on new rows?
Yes?
Idk if response to me or not..
Basically I want to be able to have multiple rows for my buttons ;D
using discord.ui.view
!d discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button 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 "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
;o
Ty ty @smoky sinew
I set the row but it doesnt seem to do anything 😦
D: still all 1 row
What did you set them to then
Serverbans is row 2,
Notes is row 1
And profile is row 3
it’s from 0 to 4
yes but they start at 0
async def sort_buttons(self):
for child in self.children:
if type(child) == discord.ui.Button:
if child.label == "Profile":
child.row = 0
child.visible = False
child.disabled = True
if child.label == "Notes Previous" or child.label == "Notes Next":
print("NOTES BUTTON!!")
print(child)
child.row = 1
print(child)
if not self.notes:
child.disabled = True
child.visible = False
if child.label == "Serverbans Previous" or child.label == "Serverbans Next":
child.row = 2
if not self.serverbans:
child.disabled = True
child.visible = False
if child.label == "Cheetos Previous" or child.label == "Cheetos Next":
child.row = 3
if not self.cheetos:
child.disabled = True
child.visible = False
<Button style=<ButtonStyle.success: 3> url=None disabled=False label='Notes Next' emoji=None row=None>
<Button style=<ButtonStyle.success: 3> url=None disabled=False label='Notes Next' emoji=None row=1>
why not set them in the decorator
any1 who could explain to me when you'll be eligble for active dev batch?
You need to have a discord bot and a support server for it
Then fill a form for it and you get it
well I've got the bot but how do I register my server as a support server for it?
ko
hi besties i am working on a command in which the main task is to ensure that people get access to channel or not. so like if parameter is None, then it gives or takes away access for everyone.
same thing for discord member and roles. but no matter how much i try this garbage doesn't work:
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Wdym it doesn't work.
if access is None, it doesn't remove those perms?
It does but for a specific role. But when access is discord.Member or discord.Role, it returns invalid
Do you know if that code is actually running?
And do you know if the Member has read_messages
i have added certain members of my server in a private channel of my server
if i use py await channel.set_permissions(role, overwrite=overwrite)
new overwrite has removes access from that channel from that role
will this overwrite also affect the members i have added to the channel?
i am using dpy
@vale wing Hey sorry for the ping but can you link to your docker article
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Top jokes non-developers will never understand
So, why is my discordbot doing this?
https://gyazo.com/585183865892ef4fd5be2a77795125ec
R u doing any setup in on_ready @drifting arrow
Im doing some things in on_ready
Am I not suppose to @gusty flax ? 🤔
Ur allowed to. Just sometimes depending on wat u setup will mess it up.
im sending some buttons to a channel 😄
In on_ready?
well it's calling a function, but essentially yes.
I think thats fine
Is easy-pil still used ?
;-; then why is bot crash and send many messages? ;-;
I think ur blocking.
rcon bot
Can't review it now, since Im in a class, but somewhere the event loop is blocked, and u aren't able to handle any discord requests.
Uh, I am trying to make my discord bot play music from youtube-dl, but i get a long error that says that it's not able to extract the id or something so it asks me to run a "--verbose" command.
this is my code:
@client.command()
async def play(ctx, url):
voice_channel = ctx.author.voice.channel
try:
await voice_channel.connect()
except:
pass
with youtube_dl.YoutubeDL() as ydl:
info = ydl.extract_info(url, download = False)
URL = info['formats'][0]['url']
voice_client = ctx.guild.voice_client
if not voice_client.is_playing():
voice_client.play(discord.FFmpegPCMAudio(url))
@client.command()
async def leave(ctx):
voice_client = ctx.guild.voice_client
if voice_client.is_connected():
await voice_client.disconnect()
also the latest version of youtube-dl is "2021.12.17" soooo I can't really update it or anything.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
:(
Last time I encountered someone trying to use it we found out it is not
hello I cant install discord-components
Use normal discord.py, it has support for components
You aren't trying to run several bots at once are you
uhh. why?
Are you
what you mean with normal discord.py can you give me exemple because I am new at doing bots
I may have several discordbots
Running from one script?
no
Yeah that's what I wanted
Okay I don't really see any blocking code but perhaps this isn't your only file
You can find examples in discord.py repository https://github.com/Rapptz/discord.py
If you need additional explanations, check out documentation https://discordpy.readthedocs.io/en/stable/
Is there anyway to make a bot join a vc with gateway and make it stream something particular
I have a question, I have a server with 3vCores 3.8GHz each. My bot is in 11k servers with high commands usage (2-5 commands per second). Is it normal that my CPU usage is cranked at 98-100%? Or something must be wrong with my code?
das a few servers there bob
Is the load surely caused by that process
I feel like this is usage for all python processes
Although don't know
Is the bot not isolated
Forget it I just said nonsense, but that still might not show the load accurately
Hey, if you've got time, could you take a look at my code?
Yeah
https://github.com/HarrisAhmed/Haknyeon Its unreadable tho. Sorry for the mess
love the commit names
I mean. its required and I don't do just one thing
- commit message is not required
- thats why you commit every small change
but if thats just solo project and you dont care too much thats fine
yea
cogs/cards.py lines 80 to 83
r1 = [id for id in piclis if data[id]["rarity"]==1]
r2 = [id for id in piclis if data[id]["rarity"]==2]
r3 = [id for id in piclis if data[id]["rarity"]==3]
r4 = [id for id in piclis if data[id]["rarity"]==4]```
The whole function is full of list comps
Time complexity of this construction is O(4n) but can be made O(n)
dam what's the alt to it ?
I think the load might be because of those unoptimized lists operations, if lists are big enough
Normal pillow
cause the ocde example im using and learning is using it
!pypi pillow
would their be any changes in the code ?
dam 😭
It actually isn't hard
background = Editor(Canvas((900, 300), color="#141414"))
profile_picture = await load_image_async(str(member.avatar.url))
profile = Editor(profile_picture).resize((150, 150)).circle_image()
poppins= Font.poppins(size=40)
poppins_small = Font.poppins(size=30)
card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]
background.polygon(card_right_shape, color="##FFFFFF")
background.paste(profile, (30, 30))
background.rectangle((30, 220), width = 650, height = 40, color="#FFFFFF")
background.bar((30, 220), max_widht=650, height=40, percentage=user_data["percentage"], color="#282828", radius=20)
background.text((200, 40), user_data["name"], font=poppins, color="#FFFFFF")
background.rectangle((200, 100), width=350, height=2, fill="#FFFFFF")
background.text((200, 100),
f'Level - {user_data["Level"]} | XP - {user_data["xp"]}/{user_data["next_level_xp"]}',
font = poppins_small,
color = "#FFFFFF"
)
the changes in this would be ?
You need to look at pillow's docs
class CogView(discord.ui.View):
def __init__(self, *, cogs: Mapping[str, commands.Cog]) -> None:
self.cog_select = discord.ui.Select(
custom_id="cog", placeholder="Choose a cog..."
)
for cog in cogs:
self.cog_select.options.append(discord.SelectOption(label=cog[0]))
self.add_item(self.cog_select)
what's wrong with this
the error is https://paste.pythondiscord.com/nakafuyama
you've got no super().__init__(...)
thanks
:)
they might and might not. that is why there is an else statement for isinstance
Ye, but u said its not hiding the channels, right?
If it is discord.Member
Hey @signal wraith!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
So.. I wanted to create a discord bot that would automatically create a thread when this specific bot sent a message in a specific channel, I asked Chatgpt and went through many errors and finally stopped getting errors, But I think chatgpt is outdated (with 2021 threads) So please help me fix this:
https://paste.pythondiscord.com/qefavowede
why do you not have any indentation
i cannot read it like this
uh what-
do you know how python indentation works
no 😔
Are questions about self bots using DISCUM or discord.py-self aloud here?
no
self bots are not allowed so questions are not allowed as well
Unfortunate
If anyone has an experience using this and is willing to DM me I would appreciate it.
Don't seek to bypass the server rules please
Sorry no 😦
its not hiding, its not opening, its doing nothing. it returns "invalid parameters"

-mycommand
Hi. I'm having an issue getting my bot to get the right params with a class.
class Memery_Bot(commands.Bot):
def __init__(self):
self.config = Config("config.json")
intents = discord.Intents.all()
super().__init__(command_prefix='m!', intents=intents)
self.add_command(self.cmd_info)
def start_bot(self):
super().run(self.config.token)
async def on_ready(self):
print('Bot is ready.')
async def on_command_error(self, ctx, error):
print(error)
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Missing required argument: {error.param}")
@commands.command(name='info')
async def cmd_info(self, ctx):
print(ctx)
await ctx.send(
f'``Current Criteria:\n\tMaximum clip length: {self.config.max_clip_length}'\
f'\n\tRequired Upvotes: {self.config.required_upvotes}\n\tRequired Downvotes: {self.config.required_downvotes}``'
)
@commands.group(name="configure", invoke_without_command=True)
@commands.has_permissions(administrator=True)
async def configure(self, ctx):
await ctx.send('You have perms.')
async def on_message(self, message):
...
# Otherwise process commands
await super().process_commands(message)
Command raised an exception: TypeError: Memery_Bot.cmd_info() missing 1 required positional argument: 'ctx'
is it possible to even parent commands to commands.Bot?
maybe make a separate cog for the commands
class CoreCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
class DiscordBot(commands.Bot):
async def setup_hook(self):
await self.add_cog(CoreCog(self))
do cogs with with on_message though?
yeah they should
aight will do thx
as long as you use process commands
Oh one thing whats the (bot) paramater?
bots can use emojis from other servers
my bad, i meant to do CoreCog(self) but it's so you can access the bot instance
Oh thats one other thing. should I be using super() or self?
no, because super is the parent instance, and you also probably want self.process_commands instead of super().process_commands though i don't think there is any difference
Ok I will change it throughout the program
is there any way to write "ctx.author.id" with interaction?
should run() still be super()?
what do you mean by that
def start_bot(self):
super().run(self.config.token)
thanks
no just use self but you will need to use the bot instance
async def weight(interaction, weight: int): ```
i get an error at this line, i think its right? but i might be wrong
what is the error?
if you're using a cog, you will probably want self as an argument
await client.load_extension("commands.admin")
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.admin' raised an error: IndentationError: unexpected indent (admin.py, line 19)```
your function is indented
and decorator is not
decide which should be indented or outdented
aight, let me see
now i get this one
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.admin' raised an error: TypeError: parameter 'interaction' is missing a type annotation in callback 'mytag'
what is your code like
huh, is that in a cog or not
yes, it is
@smoky sinew thank you very much. Works now and much cleaner with it split into a separate cog
i removed the "self" argument on the def and it worked lmao
i thought you said the command was in a class 🫠
it is though
and the bot turned on, but it doesnt load any of the commands of that cog
can you show the full code
yeah you have to indent all of those commands to match the indentation of the class
and add self back in
how should i indent it?
one sec
thanks
it's not technically in the class if you don't indent it
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
https://paste.pythondiscord.com/ewifeheyoz like this?
Now it's all in the __init__ function
one level down
De-dent it one step so it's within the class but not within the the function
All the "async def" and "def"s should be lined up
Also should probably use an asynchronous database connector but that's a whole 'nother can of worms
this is so weird, when i indent it on the editor, the paste page does not read it, and when i indent it on the page it over indents
oh i think i got it
ok i see what the problem was, thanks
what library can get timezones and give times?
datetime?
can you change a tasks time?
I currently have
@tasks.loop(minutes=interval)
where interval is a class variable of the cog
But does that actually do anything if I change it after?
guessing not...
Is their any way I can change the time of the task loop?
i think it is passed by value, not by reference so if you change the variable nothing will happen
is a discord bot that logs chat against discord TOS? like as long as i dont use it for malicious intent, is it fine with the TOS?
That's basically one of the most common functions of discord bots
to log in case of deleted messages
yea but they recently changed tos about bots so im not sure if its banned or not
just double checking is all
idk, but they changed some stuff coz of the mee6 drama. cant remember what they changed tho
hi, I am trying to use @app_commands.Cooldown but get this error py Traceback (most recent call last): File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event await coro(*args, **kwargs) File "E:\My_stuff\Discord bots\everything bot prod\bot.py", line 62, in on_ready await bot.load_extension("cogs.fun") File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension await self._load_from_module_spec(spec, name) File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: TypeError: 'Cooldown' object is not callable
thank you
does int has a value limit? im trying to use it to store user ids but trying to do it with someone, lets say 477706869704491341 (this isnt their real user id) discord asks me to use a real integer
Hello, basically I am trying to make a clear command, it works fine and all that but sometimes it throws the following error:
https://paste.pythondiscord.com/avugalawog
this is my command script:
https://paste.pythondiscord.com/ibusonojox
no because in python everything is a bigint
try it
!e ```py
print(999 ** 999)
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
3680634882592232678947008400605218658383382320373532046559596214370256093004722315301038736145051752186913452575898963911303931894479697716458323821923660765366311320017761759779321786587036607784657658118308278769820141240229486719756781317249580644279499028104989732710307877167814674195241800407343989969529308325089341169459661201767351208231519597795368522900903774525022369908394534167906404561164711397515467500486021892910286409705747626001859502261382445301874892116158640211353120779120188446307803074622052528077377576720943206923731010325174595184975240151201651667241898167663972478241753948020282281600271006239988736674357990730546189068554604883514266113106340234890442918605103523019124266084888074623121265902068304137826645542604112663788666266537557636277965690829317856456008162368911681417749932674881717021721910727310692168816682946256794926961489769998687156714408742064272120567173730996397111689011974404165902265241927828428964154146116881873912320483277389658202659340931
... (truncated - too long)
Full output: https://paste.pythondiscord.com/ugelukidip.txt?noredirect
@stone gate
I tried what you said and got this error py Traceback (most recent call last): File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 441, in _run_event await coro(*args, **kwargs) File "E:\My_stuff\Discord bots\everything bot prod\bot.py", line 62, in on_ready await bot.load_extension("cogs.fun") File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension await self._load_from_module_spec(spec, name) File "C:\Users\grand\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'checks'
code
@app_commands.command(description= "Beg people to give you coins")
@app_commands.checks.cooldown(1,45)
async def beg(self, interaction: discord.Interaction):```
i actually used str since im not using it for any maths or anything, i just want the UID to match between the user and the database
are you using discord.py?
me? ye
me yes
why not just store it as a bigint
it's never going to exceed a few digits
eh, if it works why break it ig
I am trying to create a response from the bot that includes buttons. I am taking data from a database and want to display each database row as 1 button. I am able to create the buttons using a for loop in the list created by fetchall() but now how do I attach each newly created button a function.
@bot.command()
async def cancel(ctx):
sql = 'SELECT * FROM `orders` WHERE USER_ID = ' + '"' + str(ctx.author.id) + '"' + ' AND STATUS = "ORDERED"'
cursor.execute(sql)
list = cursor.fetchall()
CancelEmbed = discord.Embed(title="CLICK A NUMBER TO CANCEL!", color=discord.Color.red())
view = discord.ui.View()
for order in list:
button = discord.ui.Button(label=order["NUMBER"])
#need to add every new created button a function or some lines of code to run.
#will work with some api. every number has its own ID and will get info based on the number clicked which will send and receive info based on the individual ID.
view.add_item(button)
await ctx.send(embed=CancelEmbed, view=view)
when playing around with button.callback i could get some results but not what i was looking for. I would get 1 function for all the buttons created.
can you show your imports
can someone help?
import os
import discord
import time
import datetime
import asyncio
import random
import json
from discord.ext import commands
from discord import app_commands
ive been stuck here 2 days now
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
also as a side-note you should use an async database library
oh my bad i didn't see you already had that
I am getting the buttons.
with the correct numbers from the database
just want to add a function that when i click on a button it sends an api request to the site to actually cancel the site. i have the api code ready. im just stuck at actually implemeting the buttons with functions
you have to add a callback to the function
sent imports
class PhoneNumberButton(discord.ui.Button):
def __init__(self, *, number: str) -> None:
super().__init__(label=number)
self.number = number
async def callback(self, interaction: discord.Interaction) -> None:
pass
# custom logic here
@unreal geyser
how to link that to the buttons? and thanks for the help
you don't "link" it you just replace discord.ui.Button with PhoneNumberButton in your code
oh yeah right thanks. will give it a try right now
and then when it's clicked, the custom logic gets ran and you have access to the number variable
im
SO bad at indentations lmao
https://paste.pythondiscord.com/fixapufipu i get the inconsistent use of tabs and spaces in indentation error at line 78
nvm, i just realized i used both tabs and spaces
Nice to meet you. Let me explain: I have an idea for a discord bot/app with AI integrations that would have GREAT potential. I would like to ask you if you are open to becoming a co-founder, in order to create a full-fledged startup! Let me know ! DM opened 🙂
Hey uhm can someone tell me how I can identify consecutive messages
Uh I am bad at english but to get the idea
The 2 messages I sent above should be identified as just 1 message
And yeah you get the idea
what do you mean
you want to get notified when a user posts twice?
When a user is trying to send the msgs as 1 but sends em as 2
UH idk how to explain
yes i understand but what do you want to do when that happens
Just save the msgs
Cuz I want to I guess
what
What's the threshold interval between the messages?
I have no idea what "threshhold interval" means, sorry
i get the following error:
discord.app_commands.errors.CommandInvokeError: Command 'industria' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
https://paste.pythondiscord.com/mijekeruco this is the command giving the error
I mean - what's the maximum time between two consecutive messages you'll listen for?
Until it gets interrupted by another user, if that makes sense..
I am so sorry, I am bad at english
You probably took longer than 3 seconds to respond
just do like ```py
messages = {
channel_id: author_id
}
@client.event
async def on_message(message):
if messages[message.channel.id] == message.author.id:
# consecutive message occured
messages[message.channel.id] = message.author.id
No, that's totally not it
Yeah but then you have edge cases like, what happens if another user in another server sends a message?
And you have to deal with cache sizes too (which is why i asked about the interval)
Oh don't worry, the bot will hear only in 1 channel
it logs the channel id
why not
is there a way to get a members default name? member.display_name gives nicknames too
just member.name
what does that mean?;;;;
uhh cuz it's not, uhh I am bad at explaining my use case I guess
Uh.. your bot took longer than 3 seconds to respond?
oh ok
ah aight-
You can defer if you suspect a long running operation (>3 secs)
await interaction.defer()
# do something that takes a long time
await interaction.followup.send(...)
so if i think that:
# Check if the building status is an integer
if isinstance(building_status, int):
# Get the current day value from the 'list' sheet
current_day = self.list_sheet.acell('B1').value
# Subtract the current day value from the building status value
value = building_status - int(current_day)
# Add the message to the embed
embed.add_field(name=f'Building {building_id}', value=f'{building_type}\nLevel: {building_level}\nFaltan {value} días para que se construya')
else:
# Add the message to the embed
embed.add_field(name=f'Building {building_id}', value=f'{building_type}\nLevel: {building_level}\nStatus: {building_status}')```
will take too long, i just move it inside the defer?
So... the text message should be like
User 1 :-
Hello
hlfl
kjdxgbrkzd```
```User 2:-
hello
gkhkgr
kgrh```
```yaml
User 1:-
grgb
ebf```
The output should be
```yaml
User 1 :-
Hello hlfl kjdxgbrkzd
User 2 :-
hello gkhkgr kgrh
User 1 :-
grgb ebf```
If this makes any sense
I'm guessing it has to do with your use of a blocking database client
The 1 line leave means a new message BTW
yeah, it has to read an entire sheet, then list the results that accord to the user ID, thats what i think it might be taking a while
something like this?
hi, I am getting this error when having amount described and is in the async def
what is your code
Read the error
I did but I don't know what it means a type annotation
Type hint
Basic Python
fun.. Why did vscode not catch it?
is it possible to have an argument that contains a list of all the server members who are having a certain role? exactly like discord.member, just presents only those who have a certain role
because it's valid.. but not what you want
It's not an error that it would know
ah
how do I make a value default to one if not specified in app_commands?
equals..
so amount: int = 1?
Yes?
sure
are view button rows 0-indexed or 1-indexed
but it would be Optional[int]
0-indexed
kk
that's fine with me
What
you annotate it as Optional[int]
things with defaults always get typed as Optional
actually nvm
since it's not none
i have the following template view that i inherit from: https://paste.pythondiscord.com/anivipicon
however, the "exit" button always appears in the front
and i can't set the column of a button...
when i inherit it & add some buttons, this is what happens
i want it to be on the right instead of on the left
is this possible?
Define it after buttons that you want it to be behind
there's the problem
it's in an inherited class because i have like 10 other views with this exit button
What
.
and i inherit it like this
You might want to use composition instead of inheritance in this scenario
how so?
Maybe create a helper function that takes any view and just appends the "Exit" button to the back
i also have an interaction_check that's the same across every view
You might also be able to call super().__init__ of your child class after you've added all the buttons
class ChildView(AdventureTemplate):
def __init__(...):
self.add_item(...)
super().__init__(...)
Just take a guess here, not 100% sure if that'd work
but is this possible w/ composition?
maybe have a function that you set w/ setattr but
that seems very scuffed
How do I check for permission in app_commands?
That's what I thought but then I got a stupid error that it doesn't exist but I prob did something wrong
What error
Just let me test it out real quick
That fixed it but the py @purge.error is broken how do I fix this? It says
Pretty sure all command errors are in discord.ext.commands
However you use discord.app_commands
yes becasue i'm migrating
@purge.error
async def sendback(self, interaction: discord.Interaction, error: app_commands.CommandError):
if isinstance(error, commands.MissingPermissions):
await interaction.response.send_message(f"{ctx.author.mention}You do not have permissions to do this command.")
Yeah it is commands.CommandError assuming you have commands imported
Not the app_commands
ok
i am new to python and have made a battleship game but am getting errors
can someone please help me if i send them the code?
wrong chat sorry
I have my bot hosted on a digital ocean droplet and have for awhile, just wondering what I'm able to implement to allow me to see error codes for the bot so that I can debug when something goes wrong? Would a remote IDE connected to the server help with this?
You could have all errors send to your server channel. But if you want todo it that way you can aswell but Ide is something i do not know
It would probably be easier to just have them sent to the channel, would that just be using the try, except for every error or is there an easier way to just send the error message?
yea but then every user will have to go to the support server for them to debug. but that does work
just set up a custom logging handler
using the logging module
It's a private bot so not really an issue for the moment
Thanks, I'll look into this!
or just do that then again I've never done it I should of not just said anything
stupid question but I want to use commands.MinimalHelpCommand in slash commands how would I do that I know of the way to use the prefix for it but not using slash commands.
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
how do i add changed by <who> in on_member_update?
override stuff like on_error tree.command_error whatever it is idr view.on_error
How can I learn to make complex bots?
Hello, basically I am trying to make a clear command, it works fine and all that but sometimes it throws the following error:
https://paste.pythondiscord.com/avugalawog
this is my command script:
https://paste.pythondiscord.com/ibusonojox
this happens because you are trying to reply to slash command that has been deleted (hence the 404 error ) by channel.purge()
is it possible to make a purge command within slash command?
you can add a check argument inside the purge
here is the purge command in documentation: https://discordpy.readthedocs.io/en/stable/api.html?highlight=purge#discord.StageChannel.purge
you can create your own check to compare purged messages
Pick an API Wrapper, learn how to work with it to implement basic functions, and then just work on more projects.
how can i download numpy and pandas
i use them for my discord bot
to use bot i need to install them
i use termux
and i tried
pip install pandas```
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
It takes before and after
before is the Member object with its previous properties (before updating something) and after is the after properties (after updating something) both will return Member object
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
i know, i asking how to get the user who changed that member
is it possible to have an argument that contains a list of all the server members who are having a certain role? exactly like discord.member, just presents only those who have a certain role
i tried ctx.target.delete and shows the same error but the code works if do some normal send am i using delete in a wrong way here
what i am doing to get into the if statement is get the mention in the embed get the id on it and check if the person is the same person as the one who run the message command
that part works but the delete or edit doesnt
You can look at my template, it contains useful tools for development of "complex" bots using disnake and postgres database https://github.com/Exenifix/disnake-bot-template-postgres
Audit log works
just to say it, I don't like your project structure
k thanks, I'll check it out
Is that subjective
I mean if that's just your opinion well it's your opinion, but if there really are some objective things that could be changed for better I can take that into consideration
What
Variable store plugin is something from 2050s
Oh I just leaked I am a time traveller
Well happens
Anyways perhaps you mean a database?
Well imo you put unrelated files under the utils directory (module)
for example bot shouldn't be there
You need to learn SQL (it's easy) and then use one of databases. Personally I recommend sqlite and postgres, latter is harder to setup but more feature-rich
Where do you usually put it to
bot is normally in root since it's effectively main.py
having your entrypoint file is fine but it's normally in the same directory as your more abstract entry
i agree to disagree, if you're talking about a bot instance, yeah it should preferably be in the main file, but having a bot class ( especially one that has highly been modified through subclass) should be in a folder where you keep your objects/other utils
I follow principle of only having entrypoint and config/manifest files in root
And that's pretty common practice isn't it
For python
same
Bobux bot developers meeting
same
It highly depends on where tot store certain files since everything in one root quickly becomes a lot if you're going to use docker
im trying to log invites and get an error with this code:
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Code:
guild = bot.get_guild(GUILD_ID)
for guild in bot.guilds:
invites[guild.id] = await guild.invites()
def find_invite_by_code(invite_list, code):
for inv in invite_list:
if inv.code == code:
return inv```
seems that the error is coming from here invites[guild.id] = await guild.invites()
You must have
manage_guildto get this information.
Your bot is probably missing that permission.
oh is that something i have to edit within the application?
No, just grant your bot the permissions it needs in your server's role settings.
by this do you mean the user needs that permission?
if so could be your issue.
It's quoted from the discord.py docs, it is referring to the bot's permissions, I should have made that more clear.
I guarantee you this will scale very poorly.
how can I loop through all the posts in a forum channel?
!d discord.ForumChannel.threads
property threads```
Returns all the threads that you can see.
How do i create command categories?
Hey
How could I add reactions to embed?
@bot.slash_command(name="training", description="request a training!")
async def training(interaction: nextcord.Interaction, training: str = SlashOption(name="training", choices={"Hopeful: Induction Ceremony": "Hopeful: Induction Ceremony", "Initiate: Combat Instruction": "Initiate: Combat Instruction", "Neophyte: Lore Instruction ": "Neophyte: Lore Instruction", "Acolyte I: Disciplinary Assessment": "Acolyte I: Disciplinary Assessment", "Acolyte I: The Bloodletting": "Acolyte I: The Bloodletting", "Acolyte II: Lore Recitation": "Acolyte II: Lore Recitation", "Acolyte II: The Gathering": "Acolyte II: The Gathering", "Acolyte III: Advanced Tactics": "Acolyte III: Advanced Tactics", "Acolyte III: The Proving": "Acolyte III: The Proving"})):
embed = nextcord.Embed(title="Training request!",
description=f"Training: {training}",
colour=nextcord.Colour.green())
embed.add_field(name="by", value=interaction.user)
embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1086053799845703741/1086057416195579954/TSE_DarkCouncil.png')
# Send the message and add a reaction
message = await interaction.response.send_message(embed=embed)
await message.add_reaction('👍')
I get an error when I add a reaction
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000022221D83890>:
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\berka\Desktop\customer 2\main.py", line 33, in training
await message.add_reaction('👍')
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'PartialInteractionMessage' object has no attribute 'add_reaction'
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'PartialInteractionMessage' object has no attribute 'add_reaction'```
send_message doesn't return the whole message that was sent. You have to fetch the original message and add the reaction that way
I never used fetch message could you guide me on that?
@fading marlin
I already got pinged when you replied... no need to tag me again
mb
Looking at nextcords documentation, you can fetch the message from the partialmessage you received
well there is no fetch function
That is the fetch function
I know but in my VScode it says I need to define it
You're calling message.fetch(), right?
no interaction.fetch

