#discord-bots

1 messages · Page 242 of 1

slate swan
#

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

slate swan
#

is there a way to check if user contains a specific word in their about me? discord.py

slate swan
#

No

thin raft
slate swan
#

okay guys is there a document where i can learn to use jsonb?

#

using postgres plz?

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

sick birch
harsh marsh
#

test.option(
    name="member",
    description="Member description",
    type=discord.Member,
    required=False 
)```
#

can I set slash command option’s description like this ?

slate swan
#

how do i set this as metadata type?

#

this part is to be a jsonb part

vale wing
# slate swan how do i set this as metadata type?

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

slate swan
#

i alreday discovered how

vale wing
#

And next time I'd advise to use topic channel (#databases)

slate swan
#

sorry, i already forget that thing

harsh marsh
#

I have this error with slash command : ```

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```

#

code :

naive briar
harsh marsh
#

bruh

naive briar
#

Also, your code has a lot of blocking code

harsh marsh
#

wym

naive briar
#

What

harsh marsh
slate swan
#

^

naive briar
harsh marsh
#

u advice me to change all my http request with aiohttp?

slate swan
#

yes

naive briar
#

Just any long blocking code in general

harsh marsh
#

so once I do that the bot will do request faster and no longer show the error msg

naive briar
#

That's not how async things work

slate swan
#

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

swift acorn
#

Hello, would anyone happen to know how you can implement automod into your discord.py bot, and what's the documentation?

naive briar
#

Don't Discord already has an automod?

slate swan
swift acorn
#

Ah so just creation of rules through commands?

slate swan
#

!d discord.Guild.create_automod_rule

unkempt canyonBOT
#

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.
swift acorn
#

Thank you so much!

slate swan
#

if thats what you mean

swift acorn
naive briar
harsh marsh
# slate swan yes
    async with aiohttp.ClientSession() as session:
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'async with' outside async function```
slate swan
harsh marsh
#

im in is_acc_dead function right ?

slate swan
#

yes but its not async function

harsh marsh
#

so I just have to change def is_acc_dead with async def is_acc_dead and I won’t get this error anymore

harsh marsh
#

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```
vocal snow
slate swan
#

guys, how do i grab user id?

#

and also server id?

harsh marsh
#

with python ?

slate swan
#

yesh

slate swan
harsh marsh
#

u can’t use it

#

it will return reason access denied 😈

slate swan
#

😦

slate swan
#

the server id will associate the template with the server

#

@harsh marsh

craggy stream
#
@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

slate swan
lean harbor
#

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.

craggy stream
slate swan
#

i don't know if i will be able to help you

craggy stream
#

anyone else?

craggy stream
#

replit

naive briar
#

I mean the function

craggy stream
#

what do you mean

naive briar
#

It's a command, so just execute it

craggy stream
#

Its for testing

naive briar
craggy stream
#

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

naive briar
#

What

craggy stream
#

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

naive briar
#

Why

#

And I don't like being called brother

craggy stream
#

Ok

craggy stream
naive briar
#

Why would you do something like that

#

But it's very easy, anyway

slate swan
#

i don't know how i grab a server id, so i can associate a template to a server

#

Depends where you need it krShrug

#

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")
slate swan
#

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

slate swan
#

Ehh, no? You have the server ID

#

the problem is how i do that without it creating a new ID

slate swan
#

You seem to have everything needed to insert

#

...

slate swan
#

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

meager chasm
slate swan
#

You have everything as said

naive briar
#

lol

slate swan
#

You just need to insert your data now, as already said

meager chasm
#

which database are you using, how are you querying it

slate swan
meager chasm
#

???

slate swan
#

oh not you

#

Krypton

#

You have it...

#

oh i see

#

me when discord-bots channel

#

copy-bots

meager chasm
slate swan
#

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

meager chasm
#

have you given a type annotation to ctx

#

I doubt it will be automatically inferred

slate swan
#

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

meager chasm
#

cogs.Character has no setup function

slate swan
#

okay, then it's just a natural error when you make an empty py file in cogs

meager chasm
#

code of cogs.Character please

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

slate swan
#

@meager chasm here

#

coroutine 'main' was never awaited

naive briar
#

Only if people actually read the tracebacks

slate swan
#

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

lean harbor
#

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.

https://paste.pythondiscord.com/ikucaginix - code

meager chasm
#

what do you mean by "doesnt work"

lean harbor
#

i've not used a db.

slate swan
#

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

meager chasm
#

you get the bot instance from the setup function

slate swan
#

i see, thought if that's the case i need to use author thing

lean harbor
slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

slate swan
slate swan
#

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

meager chasm
#

or it just doesnt work at all

meager chasm
#

such as ctx.message

lean harbor
meager chasm
slate swan
meager chasm
#

wtf

#

u cant just mash random stuff together and expect it to work lol

slate swan
#

then how?

meager chasm
#

i dont know how to explain this to you, you need to learn more python for this

meager chasm
# lean harbor Yes

and then after that when you use the info command it still sends the old value?

meager chasm
#
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

meager chasm
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

meager chasm
#

!realpython object oriented

lean harbor
meager chasm
lean harbor
meager chasm
#

the item _str_ should raise an error

lean harbor
#

Ehh

meager chasm
#

{3.1f}
should give an error

smoky sinew
#

hi zeffo bro

meager chasm
#

it should be 3:1f or sometjing

lean harbor
meager chasm
#

ya but if it wasnt raising an error for u then sometjing fishy is happening

lean harbor
#

It should wait

smoky sinew
#

i like fish 🐟

lean harbor
# meager chasm ya but if it wasnt raising an error for u then sometjing fishy is happening


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))
meager chasm
#

is info and change_value command in seperate files?

unkempt canyonBOT
#
Pasting large amounts of code

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.

lean harbor
slate swan
#

This will help everyone

lean harbor
#

ye i know

#

i just couldn't be bothered to use it

meager chasm
smoky sinew
#

only pet

meager chasm
#

i like for eat

hollow parrot
#

ayo

smoky sinew
#

gross

slate swan
#

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

meager chasm
#

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

slate swan
#

well, i need to control my urge to ask before search

sullen trout
#

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?

smoky sinew
#

use edit_original_response instead

sullen trout
#

like this?

smoky sinew
#

i meant message = await interaction.original_response()

#

sorry

shrewd apex
# sullen trout

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

shrewd apex
#
await interaction.response.defer()
message = await interaction.edit_original_response(embed=embed)
await message.add_reaction("😮")
shrewd apex
#

np

dry kelp
#

How can i add a package to poetry? It won't be added

hushed galleon
#

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

dry kelp
#

i used poetry.lock, it says the exactly same thing

hushed galleon
#

does it work after deleting poetry.lock?
btw this question is more relevant in #tools-and-devops

dry kelp
#

it's still about discord-bots

dry kelp
#

like delete it then try to restart the bot?

#

mhm

hushed galleon
#

er restarting shouldnt be necessary

dry kelp
#

I really don't know how to fix this

hushed galleon
dry kelp
#

fixed

smoky sinew
#

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.

hushed galleon
#

yknow what maybe i dont understand the worth of relying on a lock file versus constraining version specifiers in requirements.txt/pyproject.toml

smoky sinew
#

¯_(ツ)_/¯

#

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.

vale wing
craggy stream
#

Whats up guys

cosmic axle
#

Where do you guys host discord.py bots? Since heroku is no more :/ I would like to try other free options

smoky sinew
#

also heroku is meant to run webservers not discord bots, you are unlikely to find any good hosting options for free

cosmic axle
#

We can use vps like digital ocean then

smoky sinew
formal basin
#

would @commands.has_permissions(manage_messages=True) work with slash commands?

smoky sinew
#

no

formal basin
#

so how would i do it?

smoky sinew
#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

@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...
smoky sinew
#

you can just search for has_permissions on the docs btw

formal basin
#

ok

formal basin
#

how can i mention a channel using a command?

formal basin
#
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

glad cradle
#

variables names clashing

formal basin
#

i needed to change the channel = client.get_channel(993925329901068391) variable

#

i fixed it now

obsidian fable
#

I defined a function in main.py, how can I use it inside an extension file?

livid hinge
#

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

livid hinge
lean harbor
#

Anybody know how to use aiosqlire

#

I tried to create a db but it didn't create it

livid hinge
#

generally it's better to define these types of functions in a separate file you import from both main and your extension file

naive briar
lean harbor
#
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

naive briar
livid hinge
#

i think that it should be inside a with block

unkempt canyonBOT
#

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.
lean harbor
naive briar
# unkempt canyon

This only fires if you do not specify any listeners for command error
pithink

hushed galleon
naive briar
#

Sounds about right

#

!d discord.on_error

unkempt canyonBOT
#

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.
livid hinge
lean harbor
livid hinge
lean harbor
#

Yea it is in the block

livid hinge
#

so it only works for commands themselves

naive briar
#

I don't see any with statement in it

lean harbor
#

wdym

naive briar
#

It's not in a with statement block

#

Do you know what that is

lean harbor
#

no idea

#

wdym

livid hinge
#

where'd you find the code

naive briar
#

I mean, you don't need it in some cases

#

You just have to close the connection yourself

lean harbor
#

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

naive briar
#

That's why you don't just copy paste

livid hinge
#

it sounds like it's not getting awaited maybe?

#

we would need to see where these functions get called from

lean harbor
livid hinge
#

the aiosqlite package?

hushed galleon
lean harbor
livid hinge
#

you have some code that calls create_connection() right

lean harbor
#

hm

#

await aiosqlite.connect('items.db')

#

doesn't this do the same thing?

naive briar
#

Yes? Why did you create the create_connection anyway

lean harbor
hushed galleon
naive briar
#

The aiosqlite.connect already does it

livid hinge
#

i'm using disnake 2.8.1

#

i think it does have views

lean harbor
naive briar
#

What does your it doesn't work mean

lean harbor
#

db

smoky sinew
#

it should

naive briar
#

Then you did something wrong

lean harbor
#

thats the code, anything wrong with it?

#

where is the db created?

naive briar
#

No, how do you call those functions

lean harbor
naive briar
#

I

smoky sinew
#

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

livid hinge
#

that does look much cleaner

lean harbor
naive briar
#

Great

lean harbor
#

i'm supposed to call it??

#

LOL I thought it just automatically created it

smoky sinew
lean harbor
#

eh..

livid hinge
#

i tried to do something similar by subclassing ui.Button but it didn't really work

lean harbor
#

where i'm i supposed to call it

#

(this is why you don't copy and paste code)

naive briar
#

When ever you need to use it

lean harbor
lean harbor
naive briar
#

They're just normal async functions

smoky sinew
#

you only need to create the connection once

naive briar
#

Why couldn't you just call them

#

Unless you can't await them, then I guess

lean harbor
#

how would you call them

smoky sinew
# lean harbor where i'm i supposed to call it

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()
smoky sinew
#

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

lean harbor
naive briar
#

It seems very basic

smoky sinew
#

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)

lean harbor
smoky sinew
#

it's closing the connection

lean harbor
smoky sinew
#

using the execute method

#

look in setup_hook for example

naive briar
#

(and also commit to commit the changes)

smoky sinew
#

i don't think it's documented on the bot

naive briar
#

Interesting, I thought they have those

smoky sinew
#

the docs are added manually lol

naive briar
#

!d sqlite3.Connection.commit

unkempt canyonBOT
#

commit()```
Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.
lean harbor
naive briar
#

Same thing, just with await yert

lean harbor
smoky sinew
#

just replace where you're using commands.Bot with Bot instead, to make sure you're using the new updated bot class

lean harbor
#

?

lean harbor
smoky sinew
#

that has nothing to do with creating the db

#

that's just because the code subclasses bot

lean harbor
#

bot = Bot()
await bot.setup_hook()

#

would you do that?

naive briar
#

No one would

smoky sinew
#

nope, setup_hook is called automatically by discord.py

lean harbor
#

i'm confused

#

so how is it going to create the db then?

naive briar
#

The await aiosqlite.connect(...)

#

Do you know how anyway in the code they sent works in general

lean harbor
#

but it didn't create it.

#

wheres the database created

naive briar
#

In the same directory as the python file that's calling the connect

obsidian fable
smoky sinew
#

in the working directory

lean harbor
#

() inside that is supposed to be the python file where all my code is?

smoky sinew
#

the file can literally be empty

lean harbor
smoky sinew
#

it doesn't matter because it's empty

#

but it's a binary format

lean harbor
smoky sinew
#

if that's your working directory then yes

#

can you show your code now

lean harbor
#

can i rename it

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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.

smoky sinew
#

you should rename it to something more generic, like galleon.db or galleon.sqlite3 because you should only create one database per bot

lean harbor
#

aight thanks

#

and make a / command to add items and the prices of items to the database

#

not sure how i would do that

smoky sinew
#

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

lean harbor
smoky sinew
#

?

lean harbor
#

btw this is aiosqlite right? since you named it sqlite3

smoky sinew
#

read my message again pls

#

put the bot variable after the class

smoky sinew
lean harbor
#

the class Bot() what should be in the bracket

#

shouldn't be bot i don't think

smoky sinew
#

no it shouldn't

#

also, i said after the class, like after the methods end

#

setup_hook and close are both methods of Bot

lean harbor
smoky sinew
#

commands.Bot

#

this is because a class can't extend itself

lean harbor
#

ah right, also.

#

Now my @bot doesn't work

#

what should i do now?

smoky sinew
#

where did you put the bot variable

lean harbor
#

block

smoky sinew
#

look back at my messages, i said after

lean harbor
#

didn't you?

smoky sinew
lean harbor
#

done.

livid hinge
#

pretty colors

lean harbor
smoky sinew
smoky sinew
lean harbor
# smoky sinew 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....

smoky sinew
#

you have to do Bot()

lean harbor
#

where?

naive briar
#

Where you're creating the instance

smoky sinew
lean harbor
naive briar
lean harbor
smoky sinew
naive briar
#

I don't know what to tell you

lean harbor
#

got a vid

livid hinge
#

what do you use to get the code block to behave like that

naive briar
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

lean harbor
smoky sinew
#

inside what

lean harbor
#

inside db

smoky sinew
#

what

lean harbor
#

where do i put that code.

smoky sinew
#

in execute

#

i already said:

with $1 and $2 being arguments to execute

#

in this case it would be ? instead

naive briar
#

In the execute meth of a cursor or connection

lean harbor
#

right

lean harbor
naive briar
#
bot = Bot()
livid hinge
smoky sinew
lean harbor
#

oh i've already done that

smoky sinew
#

yes, but you did bot = Bot(command_prefix=...) which is what caused the error

#

Bot.__init__ does not take any arguments

naive briar
#
class Bot(...):
    def __init__(*args, **kwargs):
        super().__init__(*args, **kwargs)

ducky_sphere

smoky sinew
#

pointless

livid hinge
#

!paste can you paste the whole code here

unkempt canyonBOT
#
Pasting large amounts of code

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.

naive briar
smoky sinew
#

look at what i said

naive briar
#

I don't know about you, but I always do that

smoky sinew
#

i don't think you read my messages

lean harbor
#

i know english perfectly fine, maybe not programming english

smoky sinew
# naive briar I don't know about you, but I always do that

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

livid hinge
#

thanks

lean harbor
#

didn't you tell me to do command prefix and stuff in there

smoky sinew
#

that's in super().__init__()

#

super basically refers to commands.Bot

lean harbor
smoky sinew
#

look at your paranthesis

smoky sinew
lean harbor
#

why does it need that

smoky sinew
#

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

lean harbor
#

pff

#

ye it's fine. Not a big deal

smoky sinew
#

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

lean harbor
#

Like this?

smoky sinew
livid hinge
#

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

smoky sinew
#

then you would use the insert command to add a new row

lean harbor
#

still a syntax error. why is this ;-;

lean harbor
#

?

lean harbor
smoky sinew
slate swan
lean harbor
#

ah

#

right. Thanks

smoky sinew
#
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

slate swan
smoky sinew
#

oh

slate swan
#

you don't need to make slash options as kwrdarg

livid hinge
lean harbor
#

he's a 'professional coder'

#

How i'm i supposed to view whats in my db.

#

💀

slate swan
#

download the sqlite viewer vscode extension

smoky sinew
#

which is the opposite of plaintext

lean harbor
lean harbor
smoky sinew
#

you can read binary as hex or hex as binary

lean harbor
#

thanks

smoky sinew
rustic onyx
#

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 🙂

slate swan
smoky sinew
#

latest commit was 10 hours ago lol

slate swan
rustic onyx
#

oh lmao

#

heard of hikari before

#

how do I know whats best for me

#

is there a doc out there that compares them maybe ?

lean harbor
#

@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

smoky sinew
#

whatever you do don't use pycord

slate swan
# rustic onyx how do I know whats best for me

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

livid hinge
#

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)
lean harbor
# smoky sinew make sure to sync

@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

smoky sinew
rustic onyx
#

thanks a lot

smoky sinew
#
@commands.is_owner()
@bot.command()
async def sync(ctx: commands.Context) -> None:
    await bot.tree.sync()
    await ctx.send("Synced the bot tree.")
lean harbor
naive briar
#

on_ready can be called multiple times

#

And you shouldn't sync automatically, you should do it manually

slate swan
#

😏 personally i prefer making post requests to discord to add slash commands, f library's internal syncing

smoky sinew
lean harbor
#

aight

lean harbor
smoky sinew
#

yes

lean harbor
# smoky sinew 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?

naive briar
#

Where are the placeholders

smoky sinew
#

multi-line string also yeah placeholders

#

i also already shared an example of insert..

#

🫠

lean harbor
#

;-;

lean harbor
# smoky sinew multi-line string also yeah placeholders


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?

smoky sinew
#

sure but what is your_table_name

#

and why would you use except Exception as e:

#

you are losing the traceback this way

lean harbor
#

actually.

naive briar
#

Then why did you put it there yert

lean harbor
#

i don't think.

smoky sinew
#

yes you do

lean harbor
#

no it's called items

naive briar
#

One should be created when discord.py calls the setup hook

lean harbor
#

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?

smoky sinew
#

make the columns lowercase

lean harbor
#

Ok.

naive briar
lean harbor
lean harbor
rustic onyx
#

seems like my safest and best bet is d.py right??

naive briar
#

Whatever you prefer and familiar with

smoky sinew
odd jasper
#

zh

rustic onyx
#

not familiar with none of these libs

smoky sinew
#
ALTER TABLE items
RENAME COLUMN GalleonPrice TO galleon_price;
lean harbor
smoky sinew
#
ALTER TABLE items
RENAME COLUMN StrongScrollPrice TO strong_scroll_price;
odd jasper
#

Why doesnt my Bot work?

lean harbor
smoky sinew
odd jasper
smoky sinew
#

read it

odd jasper
#

I dont get it

#

i already red itr

naive briar
#

People just don't want to look at red texts

#

The error explained it in plain English

smoky sinew
#
'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.'
lean harbor
#
@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

smoky sinew
#

did you sync properly

lean harbor
#

shit

#

didn't sync

odd jasper
#

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.

smoky sinew
lean harbor
#

nvm

smoky sinew
#

if you're on web, clear your cache

lean harbor
#

let me stop my repl bot

smoky sinew
#

why are you using replit

#

or not

#

i'm guessing you meant replit

odd jasper
#

What

#

So what is wrong

odd jasper
lean harbor
smoky sinew
#

bruh

smoky sinew
#

i just said it

rustic onyx
#

hey guys do u recommend reading d.py's docs or watching a tutorial?

slate swan
#

docs

rustic onyx
#

k

naive briar
#

And the error literally just explained how to solve itself

lean harbor
smoky sinew
lean harbor
#

cries.

smoky sinew
#

you literally read and go to the click it showed

smoky sinew
# lean harbor

stop doing the except thing bruh you're ignoring the traceback

odd jasper
smoky sinew
#

either print the traceback or just have the error be raised

lean harbor
smoky sinew
smoky sinew
slate swan
smoky sinew
#

also your table is called items

lean harbor
# smoky sinew yes that would be the best

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?

smoky sinew
#

delete the full thing..?

#

also it will only send one and error for the other

lean harbor
#

oh

#

right i get what you mean

smoky sinew
#

like delete the error part

rustic onyx
#

what d.py version do u guys recommend, the development one or just the stable

lean harbor
rustic onyx
lean harbor
#

💀

smoky sinew
naive briar
unkempt canyonBOT
smoky sinew
lean harbor
#

mhm.

odd jasper
#

Doesnt work

#

shit englih

#

shit discord bot

#

shit pyhton

lean harbor
lean harbor
odd jasper
#

i missclicked and everything is gone

#

i dont contuine

#

bye

lean harbor
#

WAIT EASY FIX

#

🤣

smoky sinew
lean harbor
# smoky sinew 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?

smoky sinew
#

else for what

#

you just de-indent it

lean harbor
# smoky sinew else for what

@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.")
smoky sinew
#

WHERE name = ?* btw

odd jasper
#

I have my code back

#

nice and it work

smoky sinew
#

and Item GalleonPrice and StrongScrollPrice need to be replaced

lean harbor
smoky sinew
#

figure it out with your database schema

odd jasper
#

Now i have like this..
What do i need to add and where that the bot gives u a specific role on joining server

smoky sinew
#

@vocal snow is experienced with role

vocal snow
#

enable member intents and use the on_member_join event

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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.
vocal snow
#

mudkip will help you with the rest 👍

naive briar
#

Great

lean harbor
#

LOL

odd jasper
#

Ok now this

#

1109156179311079500 thats role id

smoky sinew
#

@vocal snow

vocal snow
#

hahah

#

well you called it

odd jasper
#

now

#

1109156179311079500 thats role id

vocal snow
#

do you know what functions are

odd jasper
#

yes

#

i heard of it

vocal snow
#

so you know that a function has to be defined before you use it?

odd jasper
#

no

vocal snow
odd jasper
#

i dont have much time

smoky sinew
#

actually now that i think about it i have to go...

odd jasper
#

pls just say how i can do it

#

with a role id

vocal snow
#

we dont spoonfeed code here

smoky sinew
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
smoky sinew
#

you use get_role on the id, then use add_roles with it

#

inside the on_member_join event

odd jasper
#

Like this

odd jasper
vocal snow
smoky sinew
#

zeffo join back

formal basin
#
async def on_member_join(member):
    role = member.guild.get_role(ROLE_ID)
 await member.add_roles(role)```
slate swan
unkempt canyonBOT
#
Scoping rules

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

lean harbor
#
@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

smoky sinew
#

it should

#

you just shared your whole token

formal basin
#

@bot.event
async def on_member_join(member):
    role = member.guild.get_role(ROLE_ID)
 await member.add_roles(role)
 
odd jasper
strong knoll
#

Can anybody helpme make DM For Support bot?

strong knoll
#

or is it onlt for Discord.js

lean harbor
#

nvm it does

formal basin
odd jasper
formal basin
#

copy

vocal snow
formal basin
#

copy again

strong knoll
formal basin
#
async def on_member_join(member):
 role = member.guild.get_role(ROLE_ID)
 await member.add_roles(role)```
odd jasper
slate swan
vocal snow
lean harbor
# smoky sinew it should

Any way to format this? It looks quite ugly right now. Any way to add a picture + give it a description?

strong knoll
odd jasper
smoky sinew
#

!d discord.Embed

unkempt canyonBOT
#

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...
smoky sinew
#

look at all the methods and fields here

formal basin
odd jasper
#

doesnt wok

vocal snow
formal basin
odd jasper
strong knoll
odd jasper
formal basin
lean harbor
#

aight thanks

odd jasper
vocal snow
strong knoll
odd jasper
smoky sinew
#

are you going to keep leaking your token or what

formal basin
#

add that too

meager chasm
#

Why??

formal basin
odd jasper
#

so no error but didnt gave me a role

lean harbor
# smoky sinew yes

does the description and stuff have to be in the database? For it to change the description if a different item was called

formal basin
#

rejoin?

odd jasper
#

yes

#

u can try

smoky sinew
#

huh

odd jasper
#

u invite

smoky sinew
formal basin
odd jasper
#

cant dm yu

meager chasm
#

@odd jasper u need to enable member intents

odd jasper
#

i wanted to send

formal basin
#
async def on_member_join(member):
 role = member.guild.get_role(ROLE_ID)
 await member.add_roles(role)```
meager chasm
formal basin
meager chasm
#

Stop telling PPL to copy paste code let them use their brains

formal basin
odd jasper
odd jasper
smoky sinew
# odd jasper i did

you don't have members intent and also your code will error if someone from a different guild joins

#

no

formal basin
#

ik it look same but it not

smoky sinew
#

delete

formal basin
smoky sinew
#

it's useless

formal basin
#

ok fine

odd jasper
#

ok

#

i deleted

formal basin
#

ok now it should work

odd jasper
#

Thats final

#

Should i run

sullen trout
#

why does my one bot show that it supports slash commands and the other does not, even though they both use the same script?

formal basin
naive briar
sullen trout
naive briar
#

The command tree

odd jasper
naive briar
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
lean harbor
# smoky sinew delete

Btw whats a way to limit who can use the / command is there like a simple one line of code which does that

formal basin
naive briar
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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.
odd jasper
#

error

slate swan
#

its without ()

#

@bot.event

odd jasper
#

ok worked

#

but u need to test

#

zagag9000 join server look at my bio

formal basin
odd jasper
#

doesnt worked

smoky sinew
odd jasper
#

no role given

smoky sinew
#

!d discord.app_commands.check

unkempt canyonBOT
#

@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...
odd jasper
#

Thats code

smoky sinew
naive briar
lean harbor
sullen trout
formal basin
meager chasm
odd jasper
odd jasper
formal basin
#

how?

naive briar
formal basin
#

do it show me the error and code

naive briar
#

Remove the parentheses, leave just the @bot.event

odd jasper
formal basin
smoky sinew
formal basin
#

sorry oops

slate swan
slate swan
#

right

formal basin
odd jasper
#

Ok zagaga leave and join pls

formal basin
#

turn intents on

odd jasper
formal basin
odd jasper
#

why

smoky sinew
#

only turn on the ones you need

smoky sinew
#

because you have to verify for intents after you get guilds

odd jasper
formal basin
formal basin
odd jasper
#

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

naive briar
#

Gross

smoky sinew
#

what

smoky sinew
#

you would need only member and message content in this case

formal basin
#

i only go on there for tokens

smoky sinew
#

noted

formal basin
#

makes sense why i dont know

meager chasm
#

Why are u giving advice if u dont know

odd jasper
#

For some reason now there is an error.. i did nothing

unkempt canyonBOT
#
Pasting large amounts of code

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.

odd jasper
#

How can i let my bot 24/7 online

rugged shadow
rugged shadow
#

ah - nope. you can see if you're eligible for the GitHub student pack though, that provides free credit for some hosting providers

lean harbor
odd jasper
lean harbor
#

why?

odd jasper
#

When i have the bot for some min online then apperas an error

#

and bot go offline

odd jasper
lean harbor
#

it makes your bot on 24/7

naive briar
#

It's a website monitoring tool

tidal herald
#

guys why does it say this when its on

naive briar
#

Enable it in the code

#

Not just in the dev portal

#

!d discord.Intents.message_content

unkempt canyonBOT
#

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...

plucky sun
#

how to make dropdown menus ?

#

@vocal snow

thin raft
#

!d discord

unkempt canyonBOT
#

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.

sullen trout
#

How to make a constantly changing Discord bot rich presence?

slate swan
#

Bots cannot have rich presences

earnest swift
#

Does anyone know how to add a thumbnail or image to a embed

slate swan
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
dry kelp
#

never had this type of issue

#

nvm fixed

solar coyote
#
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?

rustic onyx
#
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 🤔

vocal snow
sullen trout
#

how can i add a footer to an embed?

rustic onyx
#

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