#discord-bots
1 messages · Page 242 of 1
It's literally a question of copy pasting, just like you did before
oh
thanks man
and, how can i make a command like
+removewarning1
Refer to point 1
That's just basic Python knowledge, nothing specifically related to bot development
is there a way to check if user contains a specific word in their about me? discord.py
No
!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.
test.option(
name="member",
description="Member description",
type=discord.Member,
required=False
)```
can I set slash command option’s description like this ?
You just create it with normal SQL query, and yeah I don't see much point in having special type, you could just save it as text, that type's only advantage is they enforce json format rules which python libs should already enforce
i alreday discovered how
And next time I'd advise to use topic channel (#databases)
sorry, i already forget that thing
I have this error with slash command : ```
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
code :
You took too long to respond to the interaction 🤷
bruh
Also, your code has a lot of blocking code
wym
What
what does it mean
^
I'd ask this in #data-science-and-ml
u advice me to change all my http request with aiohttp?
yes
Just any long blocking code in general
so once I do that the bot will do request faster and no longer show the error msg
That's not how async things work
you have to respond to the slash commands in less than 3 seconds if you need more time you should defer it
removing blocking code should get rid of this long time but still could be too long
Hello, would anyone happen to know how you can implement automod into your discord.py bot, and what's the documentation?
Don't Discord already has an automod?
yes you can create automod rules
Ah so just creation of rules through commands?
!d discord.Guild.create_automod_rule
await create_automod_rule(*, name, event_type, trigger, actions, enabled=False, exempt_roles=..., exempt_channels=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Create an automod rule.
You must have [`Permissions.manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") to do this.
New in version 2.0.
Thank you so much!
if thats what you mean


async with aiohttp.ClientSession() as session:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'async with' outside async function```
you can use async stuff only in async functions'
yes but its not async function
so I just have to change def is_acc_dead with async def is_acc_dead and I won’t get this error anymore
yes
down?
I cant use headers with aiohttp?
File "c:\Users\Administrator\Desktop\flyizz\python\discord bot\ws cmd\bot.py", line 101, in warstars
async with session.get(url, headers=headers) as response:
^^^^^^^
NameError: name 'headers' is not defined```
you have to define the headers variable
with python ?
yesh
nice api key 😈
😦
it's to associate which one is the owner of the template and which server it was made for
the server id will associate the template with the server
@harsh marsh
@client.command()
async def messeger(ctx):
await ctx.message.delete()
await ctx.guild.edit(name="Test")
try:
for channels in ctx.guild.channels:
await channels.delete()
print(Fore.GREEN + "deleted {}".format(channels))
except:
print(Fore.RED + "cant delete {}".format(channels))
while True:
await ctx.guild.create_text_channel("Test")
# pings
@client.event
async def on_guild_channel_create(channel):
while True:
await channel.send("Hi")
I want the function 'messeger' to get ran first, and when the execution is over i want the client event to get ran
@slate swan
in this case you could put the messeger to first before any other function calling or any stuff
Trying to code a bot which can show the information and the value of a specific item in a game. The info command works but the change value command doesn't work. Is this because i don't have a db? But i don't think you need a db.
sorry im new, how do i do that. There is a thing like await in the library but that doesnt work. I want the messeger to be executed fully which doesnt work with await
well, i'm also new
i don't know if i will be able to help you
anyone else?
Where would you run it from
replit
I mean the function
what do you mean
It's a command, so just execute it
Its for testing
i do on my server, i want the channels to be created first then the message
together they are slow
one by one they go by faster
What
Brother
one part creates channels, other sends messages in that channels
currently it creates a channel and types a message in it at once
i want it to finish creating all channels first then send the message in each
Ok
for speed?
i don't know how i grab a server id, so i can associate a template to a server
Depends where you need it 
i need it to associate it to which server owns the template
What template
character template, like:
name:
age:
gender:
height:
weight:
(and so on...)
so each server would have their own template
Then, when a user creates such a template, save the server ID
yes
You have user interaction - you have server ID
thought for servers it would be a thing for those who are admins
Doesn't change anything
yes, so my database can keep track of which server a template X belongs to
I mean that's nice
like, if it belongs to minecraft discord server it will associate it to the server
What's your question though? You have the server ID, you have the template - you can associate them
yes
my question is how i do it
the command for that
No command needed
You do it directly when a user creates the template
well, then i don't know how i do it
doing it directly when a user creates a template
?
You have the user create a template
You save that template and assign the server ID to that template
i have this to test:
@commands.command(aliases = ['template.create'])
async def create_template(self, ctx):
data = {
"name": "",
"age": "",
"gender": ""
}
user_id = bot.client.user.id
server_id = ctx.message.guild.id
await ctx.send(f"Template Created")
but how i do that?
You create a new row into your database or something
Ideally you create a unique ID for the template and associate the server ID to that unique ID you've generated in your database.
Then you can get the server ID baed on the template ID. And get the template ID based on the server ID.
okay, i'm totally confuse
Then you have for example a row like that
| server_id | template_id |
|--------------------|-------------|
| 267624335836053506 | jHGSZWkbjw |
| 613425648685547541 | iuh43jklSH |
i have this
guess you are telling me to generate server id by it's own
Ehh, no? You have the server ID
the problem is how i do that without it creating a new ID
You just need to insert your data in the database according to that screenshot
You seem to have everything needed to insert
...
but it's what i'm planning to do
Then.. do it?
INSERT INTO template(...) VALUES(...)
yeah, but when i need the server id i don't know how i stop it from generating ID
also i'm planning it to be dynamically
not doing it manuallly
but when the roleplayers use the bot
when i need the server id i don't know how i stop it from generating ID
You don't need to generate anything
why are you generating server ids in the first place
You have everything as said
lol
You just need to insert your data now, as already said
which database are you using, how are you querying it
well, i want to grab the server ID, but you says "you don't need, it already do it"
???
oh not you
Krypton
You have it...
oh i see
me when discord-bots channel
copy-bots
popcorn emoji channel
it's because it looks like this when i put it:
it's all in white color here, i don't know what i'm doing wrong
That's because you don't have intellisense properly set
And you just need ctx.guild.id, no need of message in-between
Nah it isn't
async def create_template(self, ctx: discord.ext.commands.Context):
why i'm having this error?
it was working initially, now it's giving me the error
cogs.Character has no setup function
code of cogs.Character 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 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.
Only if people actually read the tracebacks
the problem is understanding tracebacks
No, it's reading them
And then getting information out of it and use that information to find a solution
Trying to code a bot which can show the information and the value of a specific item in a game. The info command works but the change value command doesn't work. Is this because i don't have a db? But i don't think you need a db.
what do you mean by "doesnt work"
like the command works, but it doesn't change the value of the variable
i've not used a db.
okay i got it now, i can't import bot, it's a huge misstake
i was importing bot to grab id
but it didn't worked well
you get the bot instance from the setup function
i see, thought if that's the case i need to use author thing
do you know how to fix? @meager chasm
!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.
okay, this time i tried placing the context thing:
https://paste.pythondiscord.com/aheravodel
okay i discovered that i need to import or add something to my code that allows me to use the Message,author thing
nevermind jackpot
not totally jackpot
i noted that i can't grab id with: discord.Message.author.id
are you saying it doesnt work after you restart the program?
or it just doesnt work at all
of course not. you need an instance of discord.Message
such as ctx.message
doesnt work at all
does it send the message that it changed the value?
like this?
discord.ctx.Message.author
then how?
i dont know how to explain this to you, you need to learn more python for this
Yes
and then after that when you use the info command it still sends the old value?
Yep
from item_info import item_info
``` what is this import for since you're defining item_info later too?
oh nvm thats in a different module
where do i learn it?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!realpython object oriented
Imports the dictionary from item info
are you sure you sent your current code
Yes
the item _str_ should raise an error
Ehh
{3.1f}
should give an error
hi zeffo bro
it should be 3:1f or sometjing
Ye it needs :. Shouldn't it
ya but if it wasnt raising an error for u then sometjing fishy is happening
It should wait
who is fishy
i like fish 🐟
import discord
from discord.ext import commands
from discord import Embed, app_commands
from item_info import item_info
from item_info import rules
from typing import Optional
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user})')
print('------')
try:
synced = await bot.tree.sync()
print(f"Synced commands")
except Exception as e:
print(e)
@bot.tree.command()
@app_commands.describe(item= 'The item to be requested')
async def info(interaction: discord.Interaction, item: str):
item = item.strip().lower().replace(' ', '_')
if item in item_info:
embed = Embed(title=item, description=item_info.get(item))
await interaction.response.send_message(embed=embed)
else:
await interaction.response.send_message(f'Sorry, I do not have information about {item}.')
@bot.tree.command()
async def rule(interaction: discord.Interaction):
EMBED = Embed(title='`[ - Rules - ]`', description=rules, colour=0xFFFF00)
f = discord.File("C:\\Users\\Kevin Chen\\PycharmProjects\\pythonProject\\Galleon_Logo.png", filename="Galleon_Logo.png")
EMBED.set_thumbnail(url="attachment://Galleon_Logo.png")
await interaction.response.send_message(embed=EMBED, file=f)
@bot.tree.command()
@app_commands.rename(gals = "galleons", ss = "strong-scrolls")
@app_commands.describe(item = "Item to be changed", gals = "New galleon value; either this parameter or the strong scroll parameter are required.", ss = "New Strong Scroll Value; New galleon value; either this parameter or the strong scroll parameter are required." )
async def change_value(interaction: discord.Interaction, item: str, gals: Optional[int] = None, ss: Optional[float] = None):
item = item.strip().lower().replace(' ', '_')
if gals == None and ss == None:
await interaction.response.send_message("Invalid format, both value parameters are empty")
return None
if item not in item_info:
await interaction.response.send_message("This item is not yet recorded in our database")
return None
if gals == None:
item_info[item].ss = ss
await interaction.response.send_message("{} strong scroll value changed to {}".format(item_info[item].name, ss))
elif ss == None:
item_info[item].galleons = gals
await interaction.response.send_message("{} galleon value changed to {}".format(item_info[item].name, gals))
is info and change_value command in seperate files?
nope in main.py
!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.
This will help everyone
like to eat ? or liek as pets
only pet
i like for eat
ayo
gross
well, i already discovered a way
it's not ctx.messsage
but ctx.author
finally i can say: JACKPOT
thought those informations will be really valuable for me to setting up my db
ctx.author is a shortcut to ctx.message.author which you would have found out in 2 seconds if you bothered to read the docs
well, i need to control my urge to ask before search
import discord
from discord import app_commands
from discord.ext import commands
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot ist online")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message(content=f"Hey there {interaction.user.mention}!", ephemeral=True)
@bot.tree.command(name="hold_or_sell", description="Send hold or sell message")
async def hold_or_sell(interaction: discord.Interaction, shoe: str):
embed = discord.Embed(title="Hold or Sell", description=shoe, color=discord.Color.green())
embed.set_author(name=f"Von {interaction.user.name}", icon_url=interaction.user.avatar.url)
message = await interaction.response.send_message(embed=embed)
await message.add_reaction("💹")
await message.add_reaction("💶")
await message.add_reaction("🔁")
bot.run('...')
how can i fix these errors?
send_message does not return anything
use edit_original_response instead
like this?
meaning either you didn't response in 3 seconds or the response was dismissed or deleted considering ur fetching the original message it's probably the latter
and how can i fix this?
await interaction.response.defer()
message = await interaction.edit_original_response(embed=embed)
await message.add_reaction("😮")
tysm
np
follow the instructions it tells you
afaik you usually dont want to commit poetry.lock to git unless you care about everyone using exact dependency versions
Dude i did
i used poetry.lock, it says the exactly same thing
does it work after deleting poetry.lock?
btw this question is more relevant in #tools-and-devops
it's still about discord-bots
Should i regen the file?
like delete it then try to restart the bot?
mhm
er restarting shouldnt be necessary
I really don't know how to fix this
your project might use disnake but the problem you're having is with poetry, a dependency management tool
fixed
it's recommended
Application developers commit poetry.lock to get more reproducible builds.
Library developers have more to consider. Your users are application developers, and your library will run in a Python environment you don’t control.
yknow what maybe i dont understand the worth of relying on a lock file versus constraining version specifiers in requirements.txt/pyproject.toml
¯_(ツ)_/¯
it's a little weird
Either way, running install when a poetry.lock file is present resolves and installs all dependencies that you listed in pyproject.toml, but Poetry uses the exact versions listed in poetry.lock to ensure that the package versions are consistent for everyone working on your project. As a result you will have all dependencies requested by your pyproject.toml file, but they may not all be at the very latest available versions (some dependencies listed in the poetry.lock file may have released newer versions since the file was created). This is by design, it ensures that your project does not break because of unexpected changes in dependencies.
Pyproject is less strict unless all deps are ==, yk libraries sometimes do make even minor version releases that have issues
Whats up guys
Where do you guys host discord.py bots? Since heroku is no more :/ I would like to try other free options
also heroku is meant to run webservers not discord bots, you are unlikely to find any good hosting options for free
We can use vps like digital ocean then
digitalocean is paid
would @commands.has_permissions(manage_messages=True) work with slash commands?
no
so how would i do it?
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions "discord.Interaction.permissions").
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions "discord.app_commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
you can just search for has_permissions on the docs btw
ok
thanks
how can i mention a channel using a command?
async def mod(interaction: discord.Interaction, channel: discord.TextChannel):
channel = client.get_channel(993925329901068391)
await channel.send(f"<@&1101173405304246392>, {interaction.user.mention} needs help in {channel.mention}")
await interaction.response.send_message("A mod will help soon", ephemeral=True)```
im making a mod help system
but when i type the channel when i do /mod (channel) it instead mention the channel that (f"<@&1101173405304246392>, {interaction.user.mention} needs help in {channel.mention}") is sent in can someone help
variables names clashing
i needed to change the channel = client.get_channel(993925329901068391) variable
i fixed it now
for some reason i cannot get on_command_error to work
I'm trying to use something like
...
@commands.Cog.listener()
async def on_command_error(self, ctx: Context, error: CommandError):
...
it's just not getting called, instead it says "ignoring exception in on_button_click"
i even tried assigning it to bot.on_command_error and also doing it outside the cog with @bot.event
you can do from __main__ import yourfunction but you should do it from inside a function where it's used or else you'll get a circular import issue
generally it's better to define these types of functions in a separate file you import from both main and your extension file
What is that
async def create_connection():
conn = await aiosqlite.connect('items.db')
return conn
async def create_table(conn):
await conn.execute('''CREATE TABLE IF NOT EXISTS items
(Item TEXT, GalleonPrice REAL, StrongScrollPrice REAL)''')
await conn.commit()
Thats my code so far
!d discord.ext.commands.Bot.on_command_error
i think that it should be inside a with block
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
You talking to me?
This only fires if you do not specify any listeners for command error
event handlers usually dont get handled by on_command_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").
Changed in version 2.0: The traceback is now logged rather than printed.
I was talking about the aiosqlite connect(...) thing
I think it is, lemme check I just copied and pasted it from my phone
ok i guess i was confused what on_command_error does, that makes sense
so it only works for commands themselves
wdym
where'd you find the code
I mean, you don't need it in some cases
You just have to close the connection yourself
searched it up
but the problem is this code ain't correcting the db
when i put print("Database created") inside the first block of code it doesn't print it out
That's why you don't just copy paste
it sounds like it's not getting awaited maybe?
we would need to see where these functions get called from
kekw i mean i don't really know this pip well soooo
the aiosqlite package?
and it offers extra security through hash verification, which is a bit odd to me but granted im not the kind of user that uses multiple package indexes
how would i do that
you have some code that calls create_connection() right
Yes? Why did you create the create_connection anyway
to create the db.
btw does your lib version support views? its dpy's latest way of handling message components, and most forks support it too
The aiosqlite.connect already does it
ye ik but it doesn't work
What does your it doesn't work mean
it should
Then you did something wrong
No, how do you call those functions
return
I
return is something you do inside the function, not calling the function itself
they're asking where you're using create_connection and create_table
that does look much cleaner
i'm not calling the functions.
Great
that's how you use a function yes
eh..
i tried to do something similar by subclassing ui.Button but it didn't really work
When ever you need to use it
as a command or in the terminal or in the piece of code
always.
They're just normal async functions
you only need to create the connection once
how would you call them
i personally use this method ```py
class Bot(commands.Bot):
def init(self) -> None:
super().init(...)
self.database: aiosqlite.Connection | None = None
async def setup_hook(self) -> None:
self.database = await aiosqlite.connect("database.sqlite3")
await self.database.execute("""
CREATE TABLE IF NOT EXISTS (...)
""")
async def close(self) -> None:
await super().close()
if self.database:
await self.database.commit()
await self.database.close()
whats the class Bot?
you can extend the default commands.bot class to add your own functionality
then you can use the database variable anywhere where you have access to the bot
this seems ALOT more advanced then the code that i gave
It seems very basic
it's doing the same thing, connecting to the database, creating a table, then closing it (which is something you forgot to do in your initial code)
closing the db or you mean the table
it's closing the connection
ah right, how would you then add stuff to the db?
(and also commit to commit the changes)
i don't think it's documented on the bot
Interesting, I thought they have those
the docs are added manually lol
!d sqlite3.Connection.commit
commit()```
Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.
im just gonna copy and paste this into my code to see if it works, is aiosqlite.connect("") inside the brackets is that the name of db?
Same thing, just with await 
that's the name of the file
the database file
just replace where you're using commands.Bot with Bot instead, to make sure you're using the new updated bot class
?
how would you call it so it creates the db?
that has nothing to do with creating the db
that's just because the code subclasses bot
No one would
nope, setup_hook is called automatically by discord.py
The await aiosqlite.connect(...)
Do you know how anyway in the code they sent works in general
In the same directory as the python file that's calling the connect
is it fine if the main.py file is in a different folder?
just create the file yourself
in the working directory
() inside that is supposed to be the python file where all my code is?
the file can literally be empty
is it supposed to be text?
like this?
can i call it item.db?
can i rename it
!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.
you should rename it to something more generic, like galleon.db or galleon.sqlite3 because you should only create one database per bot
aight thanks
and make a / command to add items and the prices of items to the database
not sure how i would do that
like i said, you need to update commands.Bot to be just Bot
otherwise, the code won't work because you're still using the old bot class
so put bot = commands.Bot... after the class and change it to bot = Bot()
also super().__init__(...) here ... acts as a placeholder
you would put your prefix and intents in there
there is a unsolved refernece to 'bot'
?
no, that's different, sqlite is the database, aiosqlite is the api wrapper around it
the class Bot() what should be in the bracket
shouldn't be bot i don't think
no it shouldn't
also, i said after the class, like after the methods end
setup_hook and close are both methods of Bot
what should it be?
where did you put the bot variable
look back at my messages, i said after
didn't you?
done.
pretty colors
will that work now
it's catppuccin lol
should work
how would i make a /add item command to add a item and the price of it in the db? Or can i just paste in a dictionary
TypeError: Bot.init() got an unexpected keyword argument 'command_prefix'
Ehh....
you have to do Bot()
where?
Where you're creating the instance
CREATE TABLE IF NOT EXISTS items (
guild_id BIGINT,
name VARCHAR(64),
price INT,
PRIMARY KEY (guild_id)
);
make a schema like this, and to insert use: ```sql
INSERT INTO items (name, price) VALUES (?, ?)
with $1 and $2 being arguments to execute
wt is that. Is that supposed to be a command?
Isn't sqlite3's placeholder question mark?
sorry don't quite understand
probably
You need to learn basic Python
I don't know what to tell you
what do you use to get the code block to behave like that
!code
INSERT INTO items (name, price) VALUES (?, ?)
Is this inside the db?
inside what
inside db
what
where do i put that code.
in execute
i already said:
with $1 and $2 being arguments to execute
in this case it would be ? instead
In the execute meth of a cursor or connection
right
what did you mean by where i have created the instance
bot = Bot()
that's the sql you would pass into self.conn.execute(...) as a string
where you did bot = Bot() that's creating an instance of the Bot class
oh i've already done that
yes, but you did bot = Bot(command_prefix=...) which is what caused the error
Bot.__init__ does not take any arguments
class Bot(...):
def __init__(*args, **kwargs):
super().__init__(*args, **kwargs)

pointless
!paste can you paste the whole code 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 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.
😕
look at what i said
I don't know about you, but I always do that
i don't think you read my messages
i know english perfectly fine, maybe not programming english
it's personal preference, generally it's good practice to leave the arguments customizable in case somebody else wants to use the Bot class, but most things in a discord bot are hardcoded so the class wouldn't really be useful to anyone else
thanks
but
didn't you tell me to do command prefix and stuff in there
ok understand, but now theres another error:
sqlite3.OperationalError: near "(": syntax error
look at your paranthesis
or just use this schema
what is the primary key and guild id?
why does it need that
you don't, but i assumed you wanted the items to be per-guild
if you don't, you can just remove those two lines
@lean harbor also you forgot to censor your username for the Galleon_Logo.png thing
another reason to use relative paths lol
instead of the long path you can just put Galleon_Logo.png and if it's in the same directory, it will detect it automatically
async def setup_hook(self) -> None:
self.database = await aiosqlite.connect("database.sqlite3")
await self.database.execute("""
CREATE TABLE IF NOT EXISTS items (
Item TEXT,
GalleonPrice INT,
StrongScrollPrice INT,
);
""")
```
Like this?
Noted thanks
typically sql columns are lowercase with underscores but yeah that will work
Bot supports a lot of arguments, like description, help_command, guilds, etc... you will probably want to pass more into your bot = Bot(...) callat some point, the __init__ code that catlover showed makes that work without changing your Bot class
then you would use the insert command to add a new row
sqlite3.OperationalError: near ")": syntax error
still a syntax error. why is this ;-;
Trailing comma
?
wdym
yes but you're saying changing arguments in the constructor is easier than changing them in the class
async def info(interaction: discord.Interaction, item: str):
item = item.strip().lower().replace(' ', '_')
also this won't work
you want to use an asterisk to mark item as keyword-only
otherwise it can't have spaces
interaction command
oh
you don't need to make slash options as kwrdarg
in this case it doesn't matter, the first file executed is always accessed with the name __main__ regardless of where it is
that isn't my fault lol, that was a person that was working on the bot with me
he's a 'professional coder'
How i'm i supposed to view whats in my db.
💀
download the sqlite viewer vscode extension
like i said, it's a binary format
which is the opposite of plaintext
yep binary, denary, hexadecimal
i'm not on vscode i'm on pycharm. Does repl work?
that's just how you display it, not how you store it
you can read binary as hex or hex as binary
sqlite file viewer
thanks
although you do have to make queries yourself lol
hey guys what library do u recommend to create discord bots? I used discord.py like 1 year ago but it seems like its not maintained anymore? is there maybe a better option for d.py? Thanks 🙂
you can just upload the file there :p
discord.py is maintained
latest commit was 10 hours ago lol
discord.py is maintained but there are better options like disnake ( a fork) or hikari ( another low levelled library )
oh lmao
heard of hikari before
how do I know whats best for me
is there a doc out there that compares them maybe ?
@bot.tree.command()
@app_commands.describe(item = "Item to be added", gals = "Value of the items in galleon", ss = "Value of the item in strong scrolls" )
Time to make a / command and see if it works. I will VERY LIKELY be back to eh.. ye @smoky sinew
probably just try hikari first and see if you like it
whatever you do don't use pycord
if you're looking for more community support and hybrid commands ( slash and prefix in one function ) go for discord.py
if you want ease and better class distributions go for disnake
if you want more control and strict typing with multiple command handler choices go for hikari
make sure to sync
if you wanted to do relative paths so it would work regardless of where your project is located, you could do something like;
from pathlib import Path
...
# in your function
async def ...(...):
path = Path(__file__).parent / "Galleon_Logo.png"
file = discord.File(path)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user})')
print('------')
try:
synced = await bot.tree.sync()
print(f"Synced commands")
except Exception as e:
print(e)
Thanks, already have a code for tha
that
awesome 💯
you should sync in a message command
thanks a lot
@commands.is_owner()
@bot.command()
async def sync(ctx: commands.Context) -> None:
await bot.tree.sync()
await ctx.send("Synced the bot tree.")
the bot is on 24/7 so i only need to sync it once (when i start the bot)
on_ready can be called multiple times
And you shouldn't sync automatically, you should do it manually
😏 personally i prefer making post requests to discord to add slash commands, f library's internal syncing
yeah you should run the sync command whenever you update command arguments or metadata
aight
so if my prefix was ! i can just do !sync?
yes
@bot.tree.command()
@app_commands.rename(gals = "galleon", ss = "strong-scrolls")
@app_commands.describe(item = "Item to be added", gals = "Value of the items in galleon", ss = "Value of the item in strong scrolls" )
async def add_item()
Right. So how would i go from here to be able to add a item to the db
await bot.database.execute(
"INSERT INTO your_table_name (Item, GalleonPrice, StrongScrollPrice) VALUES (, , )",
(item, gals, ss),
Like this?
Where are the placeholders
multi-line string also yeah placeholders
i also already shared an example of insert..
🫠
;-;
try:
await bot.database.execute(
"INSERT INTO your_table_name (Item, GalleonPrice, StrongScrollPrice) VALUES (?, ?, ?)",
(item, gals, ss),
)
await bot.database.commit()
await interaction.response.send_message(f"Successfully added item '{item}' to the database.")
except Exception as e:
await interaction.response.send_message(f"An error occurred while adding the item: {str(e)}")
like this?
sure but what is your_table_name
and why would you use except Exception as e:
you are losing the traceback this way
Then why did you put it there 
i don't have any tables in my db
i don't think.
yes you do
no it's called items
One should be created when discord.py calls the setup hook
ye i do
await self.database.execute("""
CREATE TABLE IF NOT EXISTS items (
Item TEXT,
GalleonPrice INT,
StrongScrollPrice INT
);
""")
it's items isn't it?
make the columns lowercase
Ok.
You just said you don't have any tables
i just checked ok
do i need to delete the db and create a new text file?
Whatever you prefer and familiar with
ALTER TABLE items
RENAME COLUMN Item TO name;
zh
not familiar with none of these libs
ALTER TABLE items
RENAME COLUMN GalleonPrice TO galleon_price;
i just deleted it and created a new one LOL
ALTER TABLE items
RENAME COLUMN StrongScrollPrice TO strong_scroll_price;
Why doesnt my Bot work?
you should do a better job at censoring that
it tells you why
I cant figure it out
read it
'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the '
'developer portal. It is recommended to go to https://discord.com/developers/applications/ '
'and explicitly enable the privileged intents within your application\'s page. If this is not '
'possible, then consider disabling the privileged intents instead.'
@app_commands.rename(gals="galleon", ss="strong-scrolls")
@app_commands.describe(item="Item to be added", gals="Value of the item in galleons", ss="Value of the item in strong scrolls")
async def add_item(interaction: discord.Interaction, item: str, gals: int, ss: float):
item = item.strip().lower().replace(' ', '_')
async with bot.database.execute(
"SELECT * FROM items WHERE Item = ?",
(item,),
) as cursor:
existing_item = await cursor.fetchone()
if existing_item:
await interaction.response.send_message("This item already exists in the database.")
return
try:
await bot.database.execute(
"INSERT INTO your_table_name (Item, GalleonPrice, StrongScrollPrice) VALUES (?, ?, ?)",
(item, gals, ss),
)
await bot.database.commit()
await interaction.response.send_message(f"Successfully added item '{item}' to the database.")
except Exception as e:
await interaction.response.send_message(f"An error occurred while adding the item: {str(e)}")
Any reason this isn't working? Since i don't see the / command add_item
prob did something wrong
did you sync properly
are you all stupid I'm not really familiar with python and I get teased that I don't read. I read the error a long time ago but still don't understand it.
It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page.
nvm
still doesn't work
😭
refresh your discord client then
if you're on web, clear your cache
let me stop my repl bot
there
i'm using replit to have my bot on 24/7 and then i've ran my code from pycharm i guess there might be a interference
bruh
docs
k
Do you really have to that be rude
And the error literally just explained how to solve itself
it has nothing to do with python
cries.
you literally read and go to the click it showed
stop doing the except thing bruh you're ignoring the traceback
What should i do.. I dont understand "enable the privileged intents" my english is not that good
either print the traceback or just have the error be raised
should i just remove it?
yes that would be the best
it has steps to enable it too.
https://gist.github.com/advaith1/e69bcc1cdd6d0087322734451f15aa2f#getting-privileged-intents
also your table is called items
await bot.database.commit()
await interaction.response.send_message(f"Successfully added item '{item}' to the database.")
await interaction.response.send_message(f"An error occurred while adding the item: {str(e)}")
But then this doesn't seem right
it's going to send 2 messages
anything i could replace it with?
wdym..how i'm i supposed to know if it didn't add it?
oh
right i get what you mean
like delete the error part
2.2.3
SyntaxError: expected 'except' or 'finally' block
thats the stable one right?
💀
i guess but latest would be more like the master branch
!pip discord.py
remove the try part too... and the indent.
mhm.
but then where is that part of the code supposed to go
LOL, whats wrong
git
if i remove the try part then where is it supposed to go this part of the code:
await bot.database.execute(
"INSERT INTO your_table_name (Item, GalleonPrice, StrongScrollPrice) VALUES (?, ?, ?)",
(item, gals, ss),
)
await bot.database.commit()
await interaction.response.send_message(f"Successfully added item '{item}' to the database.")
would an else work?
@bot.tree.command()
@app_commands.rename(gals="galleon", ss="strong-scrolls")
@app_commands.describe(item="Item to be added", gals="Value of the item in galleons", ss="Value of the item in strong scrolls")
async def add_item(interaction: discord.Interaction, item: str, gals: int, ss: float):
item = item.strip().lower().replace(' ', '_')
async with bot.database.execute(
"SELECT * FROM items WHERE Item = ?",
(item,),
) as cursor:
existing_item = await cursor.fetchone()
if existing_item:
await interaction.response.send_message("This item already exists in the database.")
return
await bot.database.execute(
"INSERT INTO items (Item, GalleonPrice, StrongScrollPrice) VALUES (?, ?, ?)",
(item, gals, ss),
)
await bot.database.commit()
await interaction.response.send_message(f"Successfully added item '{item}' to the database.")
WHERE name = ?* btw
and Item GalleonPrice and StrongScrollPrice need to be replaced
now delete it
with?
figure it out with your database schema
Now i have like this..
What do i need to add and where that the bot gives u a specific role on joining server
@vocal snow is experienced with role
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
mudkip will help you with the rest 👍
Great
LOL
@vocal snow
do you know what functions are
so you know that a function has to be defined before you use it?
no
ok mudkip will teach you about it
i dont have much time
actually now that i think about it i have to go...
we dont spoonfeed code here
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
you use get_role on the id, then use add_roles with it
inside the on_member_join event
Like this
How to make events: https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.event
on_member_join event: https://discordpy.readthedocs.io/en/stable/api.html#discord.on_member_join
Member.add_roles: https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.add_roles
is this right?
you can't just make up some random shit and expect it to work
zeffo join back
async def on_member_join(member):
role = member.guild.get_role(ROLE_ID)
await member.add_roles(role)```
in python we dont use {} to declare scope we use indentation instead
A scope defines the visibility of a name within a block, where a block is a piece of python code executed as a unit. For simplicity, this would be a module, a function body, and a class definition. A name refers to text bound to an object.
For more information about names, see /tag names
A module is the source code file itself, and encompasses all blocks defined within it. Therefore if a variable is defined at the module level (top-level code block), it is a global variable and can be accessed anywhere in the module as long as the block in which it's referenced is executed after it was defined.
Alternatively if a variable is defined within a function block for example, it is a local variable. It is not accessible at the module level, as that would be outside its scope. This is the purpose of the return statement, as it hands an object back to the scope of its caller. Conversely if a function was defined inside the previously mentioned block, it would have access to that variable, because it is within the first function's scope.
>>> def outer():
... foo = 'bar' # local variable to outer
... def inner():
... print(foo) # has access to foo from scope of outer
... return inner # brings inner to scope of caller
...
>>> inner = outer() # get inner function
>>> inner() # prints variable foo without issue
bar
Official Documentation
1. Program structure, name binding and resolution
2. global statement
3. nonlocal statement
what is ctx
@si
oops
@bot.tree.command()
@app_commands.describe(item="Item to be deleted")
async def delete_item(interaction: discord.Interaction, item: str):
item = item.strip().lower().replace(' ', '_')
async with bot.database.execute(
"SELECT * FROM items WHERE Item = ?",
(item,),
) as cursor:
existing_item = await cursor.fetchone()
if not existing_item:
await interaction.response.send_message("This item does not exist in the database.")
return
await bot.database.execute(
"DELETE FROM items WHERE Item = ?",
(item,),
)
await bot.database.commit()
await interaction.response.send_message(f"Successfully deleted item '{item}' from the database.")
Any idea why /delete_item doesn't show? and yes i have synced it @smoky sinew
@bot.event
async def on_member_join(member):
role = member.guild.get_role(ROLE_ID)
await member.add_roles(role)
@odd jasper there fixed
?
Can anybody helpme make DM For Support bot?
ok
or is it onlt for Discord.js
nvm it does
put it like this
copy
do you know python?
copy again
yes
async def on_member_join(member):
role = member.guild.get_role(ROLE_ID)
await member.add_roles(role)```
do you know js?
if you are looking for discord.js help i would go to discord.gg/djs
have you already set up a basic bot or are you writing from scratch?
Any way to format this? It looks quite ugly right now. Any way to add a picture + give it a description?
copy @odd jasper
no
Set some bots
yes
I copyd what now
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
look at all the methods and fields here
run
doesnt wok
are you using discord.py?
show me error
error
ofc
ik this one looks the same but it isnt
aight thanks
oh ok
and how do you want the dm support to work?
Uhh, so it creates a Thread, in a specified channel.
are you going to keep leaking your token or what
Why??
so they know when the bot is online
so no error but didnt gave me a role
does the description and stuff have to be in the database? For it to change the description if a different item was called
huh
u invite
no
oh i see
cant dm yu
@odd jasper u need to enable member intents
i wanted to send
async def on_member_join(member):
role = member.guild.get_role(ROLE_ID)
await member.add_roles(role)```
copy that
The same way u enabled message content intent
ik it look same but its not
Stop telling PPL to copy paste code let them use their brains
and yeah you need to do that too
i did
how
you don't have members intent and also your code will error if someone from a different guild joins
no
ik it look same but it not
delete
why?
it's useless
ok fine
ok now it should work
why does my one bot show that it supports slash commands and the other does not, even though they both use the same script?
delete the on_ready thing
Did you sync the command tree
(assuming that you're using discord.py)
what do I have to sync?
The command tree
ok
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
Btw whats a way to limit who can use the / command is there like a simple one line of code which does that
then should be good
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
ok
doesnt worked
!d discord.app_commands.checks
no role given
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
Thats code
stop advertising
You're overriding the line 8 on_ready in line 47
inside () is the roles that is allowed to use the command?
damn okay i had 2 codes and paste them together hahaha
nope
you need @bot.event() and not @bot.event
No advertisement
no with () there is a error
error
how?
Where did you get that information
do it show me the error and code
Remove the parentheses, leave just the @bot.event
ohh im thinking of commands
just the @bot.event
sorry oops
you need intents.members set to True in order to track new members join
yes
Like this?
right
on discord developer
Ok zagaga leave and join pls
turn intents on
?
go on discord developer and turn all intents on
why
stop saying this this is the worst advice you could give
only turn on the ones you need
how?
because you have to verify for intents after you get guilds
Does it worked?
yeah server and member?
yes
nice thank you
One more thing
how can i add cmd for exm !ip that the bot gives u an embed msg with pfp of the banner and msg
idk pfp
Gross
what
what is server
you would need only member and message content in this case
noted
makes sense why i dont know
Why are u giving advice if u dont know
For some reason now there is an error.. i did nothing
thanks
!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.
How can i let my bot 24/7 online
use a hosting provider like DigitalOcean or AWS or Azure
free?
ah - nope. you can see if you're eligible for the GitHub student pack though, that provides free credit for some hosting providers
just use repl
Cant
why?
Uptimerobot
?
It's a website monitoring tool
Enable it in the code
Not just in the dev portal
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
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 to make a constantly changing Discord bot rich presence?
Bots cannot have rich presences
Does anyone know how to add a thumbnail or image to a embed
!d discord.Embed.set_image /set_thumbnail
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
while True:
await pick.wait()
if client.snakeres[ctx.guild.id][2]==player_list[0]:
print("clicked")
break
else:
print("clieck someone else")
why does this go into infinite loop if someone doesnt click instead of waiting for it again?
class Bot(discord.Client):
async def on_ready(self):
await bot.add_cog(Cogs.embed.Embed(bot))
print("Bot Ready")
bot = ...
await bot.add_cog(Cogs.embed.Embed(bot))
AttributeError: 'Bot' object has no attribute 'add_cog'
what would be the correct way to add the cog 🤔
you need to subclass commands.Bot if you want to use the commands extension
how can i add a footer to an embed?
still trying to understand d.py
I get this error when starting a pretty simple bot
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\schus\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\schus\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\Users\schus\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 460, in register_commands
await self.http.bulk_upsert_command_permissions(
File "C:\Users\schus\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 338, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
Bot Ready
class Bot(discord.Bot):
async def on_ready(self):
print("Bot Ready")
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
async def setup_hook(self):
await bot.load_extension(f"cogs.embed")
await bot.tree.sync()
print("Loaded cogs")
``` the on_message function is called whenever a message is sent, even after raising this 405 error