#discord-bots

1 messages ยท Page 230 of 1

crude nexus
#

is there some terminal command?

sick birch
#

Why do you need to constantly close it and open it?

crude nexus
#

just to edit the code

sick birch
#

But there's really nothing with re-starting the bot in development as you work on it

#

In fact it's easier and faster than having a dedicated command to shut down the bot

crude nexus
#

right so just opening and closing is faster?

sick birch
#

That's what I do, yes

#

CTRL + C, up arrow, enter restarts the bot

crude nexus
#

aight

#

thanks

smoky sinew
#

you don't want extensions

crude nexus
#

what are extensions, im very lacking in the theory

smoky sinew
#

they're just files you can load, reload, and unload in discord.py

crude nexus
#

interesting

smoky sinew
#

this provides commands for reloading extensions and debugging commands

#

and syncing slash commands if you're going to make those

crude nexus
#

maybe for later, it does seem kinda complicated

smoky sinew
tall temple
#
        async with aiohttp.ClientSession() as session:
            ofww = open(f'users_data/{ctx.guild.id}/impset/lw.json', "r")
            wfc = ofww.read()
            ff = json.loads(wfc)
            info = ff['webhook_logs']
            webhook = Webhook.from_url(f'{info}', session=session)
            await webhook.send('Hello World', username='KalKer Logs')
sick birch
#

Can you show us the contents of lw.json?

tall temple
#
{"webhooklogs": "MY WEBHOOK LINK"}
#

@sick birch

sick birch
#

Should be info = ff['webhooklogs'] then

tall temple
#

oh yeah my bad, thanks ๐Ÿ˜น

#

worked thnks

fierce light
#

quick question, how does @unkempt canyon auto close forums?

#

saves timestamp on db?

smoky sinew
#

it uses redis probably

#

or site-api

fierce light
#

oh daym

#

message.author?

#

nope

#

its a on_message_delete

smoky sinew
fierce light
#

oh wait

smoky sinew
#

you have to check the audit log

fierce light
#

ohhhhhhh ok my bad lmao

smoky sinew
#

did you save your code..?

#

the error is not showing the same code

#

as the one you sent

fierce light
#

it says here ur using normal for loop

#

ayy lmao

smoky sinew
#

you reassigned message

naive briar
#

!d discord.AuditLogEntry

unkempt canyonBOT
#

class discord.AuditLogEntry(*, users, integrations, app_commands, automod_rules, data, guild)```
Represents an Audit Log entry.

You retrieve these via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").

x == y Checks if two entries are equal.

x != y Checks if two entries are not equal.

hash(x) Returns the entryโ€™s hash.

Changed in version 1.7: Audit log entries are now comparable and hashable.
naive briar
#

Where did you get the idea that the object has a channel attr

smoky sinew
#

๐Ÿ˜ฎ

naive briar
#

Why

smoky sinew
#

ยฏ_(ใƒ„)_/ยฏ

slate swan
#

What are some free services I can use to host a discord bot?

smoky sinew
#

does disnake keep up with upstream?

sick birch
maiden fable
smoky sinew
#

i'm not sure if that's possible

#

just check the timestamp of the audit log entry maybe and see if it's equal to the current time

#

if not then the deleter is the author

smoky sinew
#

probably

vale wing
#

There's new on audit log entry event iirc

#

!d discord.on_audit_log_entry_create

unkempt canyonBOT
#

discord.on_audit_log_entry_create(entry)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") gets a new audit log entry. You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to receive this.

This requires [`Intents.moderation`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.moderation "discord.Intents.moderation") to be enabled.

New in version 2.2.

Warning

Audit log entries received through the gateway are subject to data retrieval from cache rather than REST. This means that some data might not be present when you expect it to be. For example, the [`AuditLogEntry.target`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.target "discord.AuditLogEntry.target") attribute will usually be a [`discord.Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") and the [`AuditLogEntry.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user "discord.AuditLogEntry.user") attribute will depend on user and member cache.

To get the user ID of entry, [`AuditLogEntry.user_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogEntry.user_id "discord.AuditLogEntry.user_id") can be used instead.
hushed galleon
stone palm
#

why do i get this error?```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/tasks/init.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "/home/runner/MathBot-1/cogs/paper.py", line 414, in paper_result_check
value="\n".join((await server.fetch_member(i)).mention for i in document["approvals"]),
TypeError: can only join an iterable

vale wing
wind radish
#

is there a way to find the original message id from a button? im trying to figure this out but cant quite | edit : nvm i figured it out

stone palm
#

only one member currently but it can also have more

#

actually i think i fixed it

vale wing
#

Well good luck with finding another method (it probably doesn't exist)

vale wing
vivid axle
#

e

vivid axle
#

im trying to make a timezone command does anyone know a thing i can use to turn what the person inputs into a datetime.datetime ?

pseudo marlin
vivid axle
#

The person Input a time zone or location like london England gb or utc gmt etc and then it returns the current time at the time zone

slate swan
#

import pytz
from datetime import datetime

timezone = pytz.timezone(location)
current_time = datetime.now(timezone).strftime('%Y-%m-%d %H:%M:%S %Z')

#

Thatโ€™s a general example, where location is a string of your location

vivid axle
#

kk thanks ๐Ÿ˜„

cloud dawn
#

I just noticed the built in paid subscriptions inside bots ๐Ÿ’€

#

I mean I gotta love Discord encouraging people making their own bots!

ashen locust
#

how do i make the bot delete the command message

vocal snow
#

slash command or normal command

ashen locust
#

no like i type
!spoiler example
and it deletes the command message

#

original message*

vocal snow
#

so normal command

ashen locust
#

what is it

vocal snow
#

ctx.message gives you a discord.Message object

#

you can use it's delete method

ashen locust
#

ctx.message.delete() ?

vocal snow
#

yes

ashen locust
#

ok thanks

maiden fable
#

Discord's new UI

#

It's weird asffff

vocal snow
#

It suits you โ˜บ๏ธ

maiden fable
#

Yeaaaaa!

vale wing
#

This is my UI goofysmile

maiden fable
vale wing
#

Nothing comes

maiden fable
#

First click on the emoji

#

Then hold the preview image which comes

#

Make sure u r on the latest version

stable bough
#

Hola alguien me quiere ayudar aรบn proyecto grande con bot de Python

#

A mi MD

maiden fable
#

English only please

cloud dawn
maiden fable
#

Hahahahaha hated it?

cloud dawn
#

Yes

maiden fable
#

The same procedure

cloud dawn
#

Everything is too big and round

maiden fable
#

Lmao discord just made the UI more confusing for newbies

cloud dawn
#

I do prefer some curve ya know but it's a bit much

maiden fable
#

๐Ÿ‘€

cloud dawn
#

If it aint broke don't fix it

#

But no fr it's impossible to find channels if there are a lot lol

#

I guess the choose your channels on top is nice

#

But it's shared across desktop..

maiden fable
#

True

short silo
#

is this the correct way to load a cog ?

@bot.slash_command(name="load",guild_ids=GUILD)                    
async def load(ctx: discord.Interaction,extension:str):    
    if(ctx.author.id in ADMINS):
        try:
            print(extension)
            bot.load_extension(f'{extension}')
            await ctx.response.send_message("Cog loaded.",ephemeral=True)
        except Exception as E:
            await ctx.response.send_message(E,ephemeral=True)
            raise E
#

if so, my commands aren't being registered if i unload any command and then load it again

vocal snow
#

You also have to sync the commands

naive briar
#

What lib is that ๐Ÿง

short silo
cloud dawn
#

And you can also setup permissions outside the command and handle it your error handler.

#

And it's best to specify the error since there isn't much that can go wrong.

short silo
#

I understand. i will look into it

short silo
short silo
young dagger
cloud dawn
young dagger
cloud dawn
#

I meant in a call like this -> await get_summoner_name("na", summoner_id, "API_KEY", True)

#

I know the code you work with and you have multiple sessions each time but it's more efficient and cleaner if you make one session and keep passing that. You'd also not need to re-send the token since it's inside the session. You do need to make something if the session gets destroyed.

#

Don't know exactly what you are trying to do but when working with an API I like to have/make a wrapper for it so I don't have to make a function for each item.

young dagger
#

@cloud dawn I see. Could you review the code if I send it over to you?

cloud dawn
#

I could.

timber wren
#

why isnt the bot able to ping the role?

I have checked the follwing things: I have the role, The channel perms are correct, The bot has an admin role โœ…

#

I mean I know this isnt the right channel but like its a small doubt

#

(sorry for that it was late before I realised that ๐Ÿฅฒ )

cloud dawn
timber wren
#

sorry i am a little new :P

#

I have intents enabled if thats what you meant

#

intents = discord.Intents.all() intents.members = True intents.guilds = True intents.message_content = True intents.voice_states = True

cloud dawn
cloud dawn
cloud dawn
young dagger
short silo
#

How could i limit attachment size through a slash command ?

timber wren
#

what exactly do I do to make that work?

cloud dawn
cloud dawn
cloud dawn
short silo
timber wren
naive briar
#

!d discord.Attachment.size

unkempt canyonBOT
naive briar
timber wren
short silo
timber wren
#

!d discord.Attachment.height

unkempt canyonBOT
timber wren
#

this would help aswell about resolution i think

#

also discord.Attachment.width

short silo
#

don't really need resolution, just size limitations

cloud dawn
#

I see it also has options for sending attachments with size.

timber wren
#

so like

if discord.Attachment.size >= <limit>:
 await ctx.respond("Bro damn, its huge.... the image. The image bro")
``` ๐Ÿ’€
#

anyways @cloud dawn a lil brainstorm on my problem please ๐Ÿ˜…

naive briar
timber wren
cloud dawn
timber wren
#

wait let me send you my code

#
@discord.slash_command(name ='test1', description="this is a test command :D")
    async def test(self, ctx):
        embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : `/bump`")
        await ctx.respond("<@&1083433733857755269>", embed=embed)
#

theres a high chance something maybe wrong here

#

this is pycord btw

cloud dawn
cloud dawn
#

Ig try that, it shouldn't matter but if you think it's the bot itself.

timber wren
#

@cloud dawn so... ctx.respond does not allow a ping

#

but ctx.send did

cloud dawn
#

That's... odd

timber wren
#

the interaction failed because i did not mention ctx.responf

#
@discord.slash_command(name ='test1', description="this is a test command :D")
    async def test(self, ctx):
        guild = self.client.get_guild(1075617310540308583)
        role = utils.get(guild.roles, id=1083433733857755269)
        embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : /bump ")
        await ctx.send(role.mention)
#

but neverminf

#

I was just checking if this would work

#

originally this embed and ping was meant for a bump reminder message, that would be triggered a certain message in a channel

#

thanks @cloud dawn for all suggestions :)

cloud dawn
#

np :)

short silo
#

what would i need to unload a command ?

#
@bot.slash_command(name="unload",guild_ids=GUILD)
@commands.is_owner()                    
async def unload(ctx: discord.Interaction, extension: str):
    await ctx.response.defer(ephemeral=True)
    bot.unload_extension(f'{extension}')
    await ctx.followup.send("Cog unloaded.", ephemeral=True)
#

i have also tried syncing

young dagger
#

@cloud dawn Should I keep on_ready in this code or move it somewhere else?

class MyClient(commands.Bot):
    async def setup_hook(self):
        update_elo_ratings.start()
    async def on_ready(self):
        print('Bot is ready!')```
rugged shadow
#

why would you ever need to unload a command

cloud dawn
short silo
#

after making modifications

cloud dawn
wicked atlas
cloud dawn
#

Disnake even has a dev mode that auto reloads cogs on change.

short silo
#

pycord lib

wicked atlas
#

I see

simple plume
#

Helllo! Yesterday I changed my discord bots image on the developer portal, but the image does not change.. Does anybody knows how I can solve this?

tall temple
proud apex
#
class PaginationView(discord.ui.View):
    current_page : int = 1
    sep : int = 6

    async def send(self, interaction: discord.Interaction):
        self.message = await interaction.response.send_message(embed=self.create_embed(self.data), view=self)
        await self.update_message(self.data[:self.sep])

    async def update_message(self, data):
        self.update_buttons()
        await self.message.edit(embed=self.create_embed(data), view=self)
       

    def create_embed(self, data):
        embed = discord.Embed(title=f"๐Ÿ“‘ information ({self.current_page} / {int(len(self.data) / self.sep) + 1})")
        for item in data:
            embed.add_field(name="testing", value="test", inline=False)
        return embed
await self.message.edit(embed=self.create_embed(data), view=self)

๏ปฟAttributeError: 'NoneType' object has no attribute 'edit'```
how to fix it so that the post is editable?
naive briar
#

!d discord.InteractionResponse.send_message - the method doesn't return the sent message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
naive briar
# tall temple huh ?

!e

import json

string = """{
    "cat": "meow\nuwu"
}"""

print("Doesn't error")
json.loads(string, strict=False)

print("Error")
json.loads(string)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Doesn't error
002 | Error
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 11, in <module>
005 |     json.loads(string)
006 |   File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
007 |     return _default_decoder.decode(s)
008 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^
009 |   File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
010 |     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
011 |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/edolividen.txt?noredirect

naive briar
#

!d json.loads

unkempt canyonBOT
#

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *s* (a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray") instance containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

The other arguments have the same meaning as in [`load()`](https://docs.python.org/3/library/json.html#json.load "json.load").

If the data being deserialized is not a valid JSON document, a [`JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError "json.JSONDecodeError") will be raised.

Changed in version 3.6: *s* can now be of type [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray"). The input encoding should be UTF-8, UTF-16 or UTF-32.

Changed in version 3.9: The keyword argument *encoding* has been removed.
tall temple
#

??

naive briar
proud apex
proud apex
#

help please

tall temple
#

it's working for my other script, but this not for this one idk why

fading egret
#

anyone knows if there is something like this for a app_commands.Group?


class itemFunctions(app_commands.Group):

    async def cog_app_command_error(self, interaction, error) -> None:
        if isinstance(error, app_commands.errors.CommandOnCooldown):
            embed = discord.Embed(
                description=f"โŒ | Youre repeating to fast! **Retry in {round(error.retry_after)} seconds**!",
                color=error_color)
            await interaction.response.send_message(embed=embed, ephemeral=True)
        else:
            print(error)

of course this one is for a cog

tall temple
#
Traceback (most recent call last):
  File "C:\Users\user\Documents\calculator\main.py", line 10, in <module>
    config = json.load(open("config.json", encoding="utf-8"))
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 4 column 1 (char 126)
#

huh ?

dry arrow
#

anyone want to create a gambling bot?

#

with me

slate swan
#

import discord
from discord.ext import commands

bot = commands.Bot(intents=discord.Intents.all())

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')

bot.run('bot token lol')

i haven't kept up with slash commands, can anyone please tell me how to make a slash command?

slate swan
#

is there a way to add {} into the modal pop up? doing a welcome command with different variables and stuff

#

anyone know how to make a slash command with like
/mute user:id duration:60d

#

like how do i make a option

tall temple
glad cradle
#

it's an error about your config.json file

#

btw opening and reading a file is a blocking call, this mean that it'll block the bot's event loop

you should use something async or run that function with an asyncio thread safe function

slate swan
#
@client.tree.command()
async def hello(interaction: Interaction):
    print(f"> {Style.BRIGHT}{interaction.user}{Style.RESET_ALL} used the command.")
    await interaction.response.send_message(inspect.cleandoc(f"Hi **{interaction.user}**, thank you for saying hello to me."))```
can someone help me add an option here, doesn't matter what it is
glad cradle
#

!pypi aiofiles

unkempt canyonBOT
tall temple
#

i changed nothing

glad cradle
#

check your json file

glad cradle
tall temple
slate swan
#
{
    "bot_token" : "---MY BOT TOKEN---",
    "bot_status" : "By Medra#0002"
}```
#

try that lol

tall temple
#

oh yeah my badddddd

#

BRUH I'M SO DUMB cry_gn

#

thx my babe

slate swan
tall temple
spice carbon
#

is there a way to check the webhook "owner"? by owner i mean the integration that created it, in this case mine. i want to get all of the webhooks on a x channel that was created by myself (via TextChannel.create_webhook) and use this webhook to send a message instead of creating a new one

#

i was thinking to loop through the webhooks of a channel TextChannel.webhooks() and checking the "owner" of each one of them, them if i find one that is from my integration, i just get the url from it and construct it again with Webhook.from_url, but if you have another solution let me know

glad cradle
# slate swan i still need to know how to do this

you just need to pass them as arguments

async def hello(inter: Interaction, member: discord.Member, time: int, reason: str): ...

they will all be mandatory instead if you want to make them optional you just need to pass a default value for that argument

sick birch
#

Probably should apply a transformer to the time

unkempt canyonBOT
#

The user this webhook was created by. If the webhook was received without authentication then this will be None.

glad cradle
sick birch
#

Ye just a suggestion to OP

simple plume
#

Hello! Yesterday I changed my discord bots image on the developer portal, but the image does not change.. Does anybody knows how I can solve this?

slate swan
#

am i dumb or why does this not work?

if self.image.value is not None:
                                if not re.match(r'\b(https?://\S+\.(?:jpg|jpeg|png|gif|bmp|webp))\b', self.image.value, re.IGNORECASE):
                                    return await interaction.response.send_message("You did not provide a valid URL to an image in **Embed Image (right-placed)**.", ephemeral=True)
                            elif self.image_bottom.value is not None:
                                if not re.match(r'\b(https?://\S+\.(?:jpg|jpeg|png|gif|bmp|webp))\b', self.image_bottom.value ,re.IGNORECASE):
                                    return await interaction.response.send_message("You did not provide a valid URL to an image in **Embed Image (bottom-placed)**.", ephemeral=True)
                            else:
                                await interaction.response.send_message(f"You have successfully configured your Embed, see how it looks: `{ctx.prefix}welcome show`", ephemeral=True)
                    

in the docs it says when no text is input its None

glad cradle
#

what's not working

slate swan
#

so if self.image.value or self.image_botton.value is not None, it should match the regex etc.. but if its not it should skip that part and go to the else statement, but even if its None it still goes to the if or elif statement

#

uhm yeah.. nvm i fixed it

spice carbon
spice carbon
#

how do y'all construct embeds? out of curiosity

        embed = (
            discord.Embed(
                title="some_title",
                color=discord.Color.brand_green(),
            )
            .add_field(name="some_field", value="some_value")
            .add_field(name="another_field", value="another_value")
        )

or

        embed = discord.Embed(
            title="some_title",
            color=discord.Color.brand_green(),
        )
        embed.add_field(name="some_field", value="some_value")
        embed.add_field(name="another_field", value="another_value")
tall temple
#

how can i code button that redirect to a link ?

#

like that

glad cradle
#

!d discord.ButtonStyle.url

unkempt canyonBOT
tall temple
#

thx

toxic meteor
#

!e

unkempt canyonBOT
#
Missing required argument

code

toxic meteor
#

!e ```lua
--...

function string_split(inputstr, sep) --ln 3 (i didn't make this function)
sep = sep or "%s"
local t= {}
local pos = 0
local function next(s)
pos = pos + 1
local out = s:sub(pos, pos) --ERROR!(attempt to call method 'sub' (a nil value)) (errors when called from ln 79, but not the ln 61 call)
if out ~= "" then
return out
end
end
local cur_str = ""
local next_char = next(inputstr)
while next_char do
if next_char == sep then
table.insert(t, cur_str)
next_char = next(inputstr)
cur_str = ""
else
cur_str = cur_str .. next_char
next_char = next(inputstr)
end
end
table.insert(t, cur_str)
return t
end

--...

function deserialize(serial) -- ln59

local values = string_split(serial, "|") -- ln 61

print(tostring(#values))

if values[1] == "runlogger" and #values == 10 then
    
    local seed = tonumber(values[2])
    local death = values[3]
    local time = tonumber(values[4])
    local killed = tonumber(values[5])
    local hp = tonumber(values[6])
    local gold = tonumber(values[7])
    local x = tonumber(values[8])
    local y = tonumber(values[9])
    local wandstogether = values[10]
    
    print(wandstogether)
    
    local wands = string_split(wandstogether, "^") -- ln 79 (ERROR!!!)
            
            --...
else
    print("Invalid format!")
end

end```

#

!e ```lua
--...

function string_split(inputstr, sep) --ln 3 (i didn't make this function)
sep = sep or "%s"
local t= {}
local pos = 0
local function next(s)
pos = pos + 1
local out = s:sub(pos, pos) --ERROR!(attempt to call method 'sub' (a nil value)) (errors when called from ln 79, but not the ln 61 call)
if out ~= "" then
return out
end
end
local cur_str = ""
local next_char = next(inputstr)
while next_char do
if next_char == sep then
table.insert(t, cur_str)
next_char = next(inputstr)
cur_str = ""
else
cur_str = cur_str .. next_char
next_char = next(inputstr)
end
end
table.insert(t, cur_str)
return t
end

--...

function deserialize(serial) -- ln59

local values = string_split(serial, "|") -- ln 61

print(tostring(#values))

if values[1] == "runlogger" and #values == 10 then
    
    local seed = tonumber(values[2])
    local death = values[3]
    local time = tonumber(values[4])
    local killed = tonumber(values[5])
    local hp = tonumber(values[6])
    local gold = tonumber(values[7])
    local x = tonumber(values[8])
    local y = tonumber(values[9])
    local wandstogether = values[10]
    
    print(wandstogether)
    
    local wands = string_split(wandstogether, "^") -- ln 79 (ERROR!!!)
            
            --...
else
    print("Invalid format!")
end

end```

unkempt canyonBOT
#

@toxic meteor :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 3
002 |     function string_split(inputstr, sep) --ln 3 (i didn't make this function)
003 |                                                        ^
004 | SyntaxError: unterminated string literal (detected at line 3)
outer parcel
#

is it possible to lock certain commands away from other users that they can not see it

shrewd apex
smoky sinew
slate swan
smoky sinew
#

yes

slate swan
#

i forgot abt it thanks tho

spice carbon
#

i'm doing this to respond to a interaction without doing anything, but i feel like its a bit hacky and i shoudnt be doing this. are there other ways to do this, without editing any mesages or doing any action really?

sick birch
#

It tells Discord that you successfully received the interaction and acknowledged it, you just don't want to do anything at the moment

spice carbon
#

wont this make the bot "think"?

#

im going to try this one sec

sick birch
#

The thinking kwarg is False by dfeault

spice carbon
#

ah this works just fine, thanks

spice carbon
slate swan
#

i have certain variables stored in my db as a string, 1 example is "{user.name}", i want to convert it to the user name (i can do that), but the thing is that i normally wouldn't know which ones are stored so i need to "detect" them and convert them into the according real variable

spice carbon
#

talking about pong, what is InteractionResponse.pong() even used for? the docstring doesnt say much... could you make a example perhaps?

sick birch
spice carbon
sick birch
#

If you want to know it's used as the appropriate response to an interaction from the Discord gateway with type 1 (PING)

spice carbon
#

when does discord fires this? pithink

sick birch
#

The documentation is pretty sparse regarding that

#

I'm guessing the timing behind PING interactions is just internal

#

All the Discord API documentation says is "you must be ready to respond to a PING interaction with PONG at any time"

#

We see a similar system implemented in the gateway but it's documented better and more obvious (you need to keep ping-ponging the gateway to maintain a connection)

spice carbon
#

heartbeat?

#

guess i'm never using this method

sick birch
spice carbon
#

kk, thanks for the explanations ๐Ÿ‘Œ

slate swan
#

!d discord.Client.get_partial_messageable

unkempt canyonBOT
#

get_partial_messageable(id, *, guild_id=None, type=None)```
Returns a partial messageable with the given channel ID.

This is useful if you have a channel\_id but donโ€™t want to do an API call to send messages to it.

New in version 2.0.
slate swan
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
tall temple
#

thx

#

i found

tall temple
#

!h discord.ButtonStyle.link

#

!d discord.ButtonStyle.link

unkempt canyonBOT
tall temple
#

could you gimme an embed example with link button, i don't understand it's syntax :/

#

@sick birch ๐Ÿ˜„

gleaming shore
#

Im trying to set up a discord bot, im new to the bot things but not python,
I just cant get it to respond to my messages, I used this tutorial to get on with it https://youtu.be/hoDLj0IzZMU I even tried fixing it with the bot but it just didnt work,
Can someone take a look at my files please? Appreciate your time

Today we will be learning how we can create a Discord Bot from scratch in Python. We will host it on a local server and it will be able to respond to users in less than 15 minutes! A perfect tutorial for getting started with Discord Bots in 2022.

Developer Portal:
https://discord.com/developers/applications

00:00 Demo
01:30 Getting started
04...

โ–ถ Play video
sick birch
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

sick birch
#

The above embed is most likely the cause of your issue

young dagger
#

How do you trigger typing?

smoky sinew
#

!d discord.abc.Messageable.typing

unkempt canyonBOT
#

async with typing()```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.

Example Usage:

```py
async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(20)

await channel.send('Done!')
```  Example Usage...
smoky sinew
#

it's a context manager

dense jackal
#

Is it possible to do a leaderboard discord bot that will refreshes it every minutes or so?

smoky sinew
#

"is it possible" is a very vague question

dense jackal
smoky sinew
#

so

#

what about it

dense jackal
#

Well I want it to count how many message a user sent and be able to do a lifetime and weekly leaderboard that refreshes often

#

Is there any documentation to help me?

smoky sinew
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
young dagger
#

Is it better to use a dictionary or a tuple for returning functions?

hot cobalt
#

Those are two very different things

#

So... I guess it depends entirely on what exactly you're doing

slate swan
#

Looking for someone that can do discord bot work, paying in BTC

slate swan
#

Hey i have used buttons in my discord bot
Like someone pressed the button it will dm etc

But after sometime of posting it , the button stops working

#

Also if i edit any code in my bot it stops working

smoky sinew
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
smoky sinew
slate swan
slate swan
slate swan
smoky sinew
smoky sinew
#

you need no timeout and the add_view method is what actually makes it persistent

fringe narwhal
#

hello i seem to be having a problem with this line of code, i believe its been removed in v2 of discord.py but if anyone can help me find a replacement that would be greatly appreciated ๐Ÿ˜„

        cogs = [c for c in self.client.cogs.keys()]
        lower_cogs = []
        for cog in cogs:
            lower_cogs.append(cog.lower())
outer parcel
slate swan
#
import discord
from discord.ext import commands, tasks

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)

@bot.command()
async def bump_reminder(ctx: commands.Context, action: str):
    disboard = ctx.guild.get_member(302050872383242240)
    if ctx.channel.id != 1098629989794066486:
        await ctx.send("Use this command at the bump channel")
        return
    if not action.casefold() == "bump":
        return
    if not disboard.status == discord.Status.online:
        await ctx.send(embed=(discord.Embed(color=discord.Colour.red,description=(f"Whoa {disboard.mention} appears to be offline right now!\nI'll monitor the bump bot's status and notify everyone when it comes back online."))))
        return
    else:
        await ctx.send("thanks for bumping,disboard will be back in two hours to be bumped:)")
        await ctx.channel.set_permissions(disboard, view_channel=False)
        lock_disboard_Out_for_two_hours.start()

@tasks.loop(hours=2)
async def lock_disboard_Out_for_two_hours():
    guild = bot.get_guild(1098629989794066483)
    disboard_role = discord.utils.get(guild.roles, name="DISBOARD")
    bump_role = discord.utils.get(guild.roles, name="Bumpers")
    channel = guild.get_channel(1098629989794066486)
    await channel.set_permissions(disboard_role, view_channel=True)
    await channel.send(f"Discord is back, {bump_role.mention} come bump the server!")
    lock_disboard_Out_for_two_hours.cancel()
bot.run('token')

I am trying to make a disboard remainder bot i dont know its dont even responding, Can anyone can help me?

merry spruce
#

how should i fix missing 1 required keyword argument intents on discord py?

meager chasm
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

timber wren
#

hey i got this error

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
``` but the bot works just fine... is it concerning or do i let it be?
fringe narwhal
merry spruce
#

Improper token has been passed.

#

how about this error

naive briar
#

What about it

merry spruce
#

can anyone help me

vocal snow
merry spruce
#

to run the bot

vocal snow
#

Don't pass bot keyword argument?

vocal snow
unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
merry spruce
#

but how while i need it to enter token

#

selfbot pls

vocal snow
#

Selfbots violate discord ToS

naive briar
#

Selfbots are against ToS

vocal snow
#

We don't help with that here and discord.py does not support them

merry spruce
#

oh ok

#

but how to run the token of the bot?

vocal snow
#

Not sure what you mean by that

keen niche
merry spruce
#

i ve try to code "bot=True" but this displayed

vocal snow
#

Just don't pass it

merry spruce
#

but it cannot run...

#

if i dont pass it

vocal snow
#

What

#

What do you mean it cannot run

#

If you have a bot token and you pass it to .run() it will run

merry spruce
#

bot.run() right?

vocal snow
#

yes

#

and pass the bot token to it

vocal snow
vivid axle
#

can anyone help i get this error when i try and run my bot aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1002)')]

slate swan
#

how can i make a bot where if he sees any embed with #ff0000 he will respond i see a embed with #ff0000

vivid axle
#

dont just post the code do a pastebin

#

good

slate swan
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
vivid axle
slate swan
fading egret
vivid axle
slate swan
slate swan
slate swan
#
import discord
from discord.ext import commands
import asyncio

# URL of the image to use in the embed
embed_image_url = 'https://images-ext-1.discordapp.net/external/tAuRcs-FCy2M8OaTS9Ims62J1vrFiviahjBDtpZrrBs/https/disboard.org/images/bot-command-image-bump.png'

# Create a new bot with a command prefix of "."
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)

# Define an event handler that will run every time a message is received
@bot.event
async def on_message(message):
    # Check if the message content is "/bump"
    if message.content == '/bump':
        # Check if the message contains an embed with the specified image URL
        if message.embeds and message.embeds[0].image and message.embeds[0].image.url == embed_image_url:
            # Get the name of the user who sent the message
            author_name = message.author.name
            # Send a message saying that the user just bumped the server
            await message.channel.send(f'{author_name} just bumped the server')
        else:
            # If no embed with the specified image URL is found, send a message saying that no one bumped the server
            await message.channel.send('No one bumped the server :(')

    # Process the message as a command, if it matches the command prefix
    await bot.process_commands(message)

I am working on a bump remainder but i got a issue in the half of the development, the issue is its not even able to recognise who bump with /bump command, Any help would be appreciated.

brazen raft
#

That's not how you use slash commands

#

And because you have a Bot instance it makes sense to never write commands in an on_message event in the first place

slate swan
#

can you explain me how can i use that

slate swan
brazen raft
#

Do you want it to be a slash command, a message command or a hybrid command?

slate swan
north kiln
#

you wouldn't want to do that

tall temple
#
@bot.event
async def on_ready() :
    logschannel = bot.get_channel(config['logs_channel'])
    await bot.change_presence(status = discord.Status.dnd, activity = discord.Activity(type = discord.ActivityType.watching, name = f"{config}  | {len(bot.guilds)} servers !"))
    await logschannel.send(embed = discord.Embed(title = f"",
                                                 description = f"\โœ…  ใƒป  Bot successfully connected and able to receive commands !",
                                                 color = 0x45b557))
#

it's status didn't change :/

thin raft
vale wing
cloud dawn
#

They can't?

#

damn

vale wing
#

Actual response from bot might do that but I am not sure about that either

tall temple
#
@bot.slash_command(name="help", description="CMD used to display commands help panel")
async def help(ctx) :
    embed = discord.Embed(title = f"โ€Ž", 
                          description = f"",
                          color = 0x2c245b)
    
    embed.set_footer(text = config["footer_txt"], icon_url = config['footer_img'] )

    await ctx.respond(embed)
#

huh ?

cloud dawn
#

You printed the object repr

#

First arg will always be converted to string.

tall temple
cloud dawn
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
brazen raft
cloud dawn
#

@tall temple Look at the function.

tall temple
#

๐Ÿ˜น

#

oh yeah i put embed = embed and it worked

#

thx

cloud dawn
# tall temple could you explain ?

Well by looking at the function you can see what you need to pass in order for the function to work. In this case the first optional argument provided will be content. And in the Discord.py library it always get converted to string.

There are also multiple keyword arguments that are indicated by being after the * so in order to send the embed you need pass it along the right keyword. e.g embed=embed.

tall temple
#

yeah that's what i did

#

thanks for help man ๐Ÿซ‚

whole shoal
#

How do i reset the select drop-down menu after each iteration, cuz when the bot moves to next one and trys to add the options again, then it shows an error that the option already exists

tall temple
#
    await bot.change_presence(activity=discord. Activity(type=discord.ActivityType.watching, name = f'{config}  | {len(bot.guilds)} servers !'))
tall temple
cloud dawn
#

Uhhh kay

#

That's not good?

tall temple
#

there is no error in the console :/

slate swan
#

I'll share my discord token , and see what you guys add ! , Idc if someone just deletes the whole server

#

But it will be fun to see what ppl adds

#

Will it be creativity or destruction

#

Dm me if someone agrees to accept it , I'll dm them bot token

tall temple
#

there is a bot security

#

you can post your token here

#

try ๐Ÿ˜น

slate swan
tall temple
#

okok

slate swan
#

Nope cant

cloud dawn
#

I got it dw

#

lmfao

slate swan
#

ok

#

I can dm too tho but ok

#

Go crazy! , I wonder what it will be like

cloud dawn
#

@slate swan What intents are on?

slate swan
#

Do u mean permissions?

young dagger
slate swan
#

Or do you mean

#

@cloud dawn

#

If you mean permissions, its administrator permission

cloud dawn
#

intents

slate swan
#

The intents option that appears on dev portal is on

slate swan
#

Admin*

tall temple
#

lemme show u

tall temple
slate swan
#

Yeah these are on

slate swan
#

Public bot , and these 3 are enabled @cloud dawn

#

I also tested token its working

#

I realised

#

This isn't weird experiment at all

#

This is what 99.99% servers go through

#

Trusting random bots

#

General chat id , [#1098955638073213089](/guild/267624335836053506/channel/1098955638073213089/)

#

hey when i restart my bot the buttons dont work how to fix it?

robust ember
#

Hi there, I'm having issues with my code. I'm trying to make a roblox discord verify system. Essentially this is a "loop" where it does the following:

  1. Bot asks the user to enter their ROBLOX username.
  2. Bot reads the roblox username.
  3. Bot uses the ROBLOX API to get information about the user using this API: https://users.roblox.com/v1/users/search?keyword={username}
    (username is the definition for the message content, basically the username they provided in step 2.
  4. If the data is valid, ask if it's THEIR account.
    -> If user says YES, the code should continue to go down further the loop (you can't see it in the code I sent, it's basically the code that's below it but not apart of it)
    -> If user says NO, the code essentially resets. Basically, the code should go back to step 1 and ask for the users ROBLOX Username. All previous data should be wiped to make sure there are NO issues with calling the ROBLOX API. Essentially it should be like I just stopped the bot and turned it back on. Just not actually turning off and on, just resetting and going to step 1.
  5. Else, if the data IS NOT VALID, it should do the same as the NO statement in step 4.

My current code, which doesn't work the way I described above,


while True:
        await channel.send('Please enter your Roblox username.')
        username_message = await bot.wait_for('message', check=lambda message: message.author == ctx.author and message.channel == channel)
        username = username_message.content
        url1 = f'https://users.roblox.com/v1/users/search?keyword={username}'

        response = requests.get(url1)
        data = json.loads(response.text)

        if "data" in data and len(data["data"]) > 0:
            user_id = data["data"][0]["id"]
            print(user_id)
            while True:
                await channel.send(f'Is "{username}" your Roblox account? Please type "YES" or "NO".')
                verification_message = await bot.wait_for('message', check=lambda message: message.author == ctx.author and message.channel == channel)
                verification = verification_message.content.lower()
                if verification == "yes":
                    await channel.send(f'{username}" has been verified with Roblox ID: {user_id}')
                    break  # Exit the inner loop and continue with the command
                elif verification == "no":
                    await channel.send('Please enter your Roblox username.')
                    break  # Exit the inner loop and restart the command
                else:
                    await channel.send('Invalid input. Please type "YES" or "NO".')
        else:
            await channel.send(f'Sorry, {username} could not be found on ROBLOX.')
cloud dawn
# slate swan All three of these
import asyncio
import logging

import discord
from discord import Intents, Game
from discord.ext.commands import Bot

logging.basicConfig(encoding="utf-8", level=logging.DEBUG)


class Dispy(Bot):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    @property
    def latency(self) -> int:
        return int(super().latency * 1000)

    async def on_ready(self) -> None:
        logging.info(f"Ready, {self.latency}ms")
        await self.change_presence(activity=Game(name="YEEEEEEEEEEEEEET"))

    async def setup_hook(self) -> None:
        self.app_info = await self.application_info()
        logging.info(
            f"Starting {self.app_info.name} using discord.py {discord.__version__} - {discord.__copyright__}"
        )


bot = Dispy(command_prefix="!", intents=Intents.all())


async def main() -> None:
    async with bot:
        await bot.start(
            "MTA4NjY2NDA5NzY3Nzk4Nzk5MA.GdqSn   Remove spacing   b.maGqaUtglD8Mkk1aDGV2nP8dktbNCD7YqX-llg"
        )


if __name__ == "__main__":
    asyncio.run(main())
#

Here a template for everyone lol

whole shoal
#

Anoynne knows How do i reset the select drop-down menu after each iteration, cuz when the bot moves to next one and trys to add the options again, then it shows an error that the option already exists

cloud dawn
#

Explain in more detail

#

Like what is happening.

whole shoal
#

Ill show the error once I reach home

stone palm
#

how to i add a path for an image as a thumbnail url?

#

theres a folder called assets and inside that theres an image called image.png

whole shoal
#

does url="/assets/img.png" work?@stone palm

whole shoal
#

@stone palm i have an alternate way for that, upload image to a random discord dm or server then copy that media link and paste in url

stone palm
whole shoal
#

True maybe wait till someone knows it

cloud dawn
#

@stone palm```py
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)

tall temple
#
noring exception in command calculate:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\user\Documents\calculator\main.py", line 93, in calculate
    invite = await guild.channels[0].create_invite
TypeError: object method can't be used in 'await' expression

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: object method can't be used in 'await' expression
#
    if sign != "A" or sign != "D" or sign != "S" or sign != "M" or sign != "a" or sign != "d" or sign != "s" or sign != "m" :
        guild = bot.get_guild(ctx.guild.id)
        invite = await guild.channels[0].create_invite
        print(Fore.RED + f"Unsuccessfully calculated for {ctx.author} in {ctx.guild.name} server !")
        logsua = bot.get_channel(config['logs_users_actions'])
        await logsua.send(embed = discord.Embed(title = f"",
                                            description = f"\๐Ÿ’ก  ใƒป  Bot unsuccessfully calculated for `{ctx.author}` in [`{ctx.guild.name}`]({invite}) server !",
                                            color = 0x759fff))
#

huh ?

cloud dawn
#
if sign != "A" or sign != "D" or sign != "S" or sign != "M" or sign != "a" or sign != "d" or sign != "s" or sign != "m" :
``` ==
```py
if sign.lower() not in "adsm":
tired pollen
#

Is there any way i can get guild preview with guild id?

cloud dawn
#

It's a function

tall temple
#

oh yeah

tired pollen
slate swan
#

i am getting
TypeError: 'function' object is not subscriptable

naive briar
#

!e

def func(): ...

func[0]
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     func[0]
004 |     ~~~~^^^
005 | TypeError: 'function' object is not subscriptable
naive briar
cloud dawn
tired pollen
#

Sad

#

Anyway thanks for helping

cloud dawn
#

You can make a raw request tough

tired pollen
#

Yea I'll

tall temple
#

@cloud dawn ```py
Ignoring exception in command calculate:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\user\Documents\calculator\main.py", line 93, in calculate
invite = await guild.channels[0].create_invite()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1244, in create_invite
data = await self._state.http.create_invite(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 367, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel

#

nvm i just put 1 instead of 0

#

it worked tysm

slate swan
#

TypeError: vouchbtn.init() missing 1 required positional argument: 'data'

class disbot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(vouchbtn())
    

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')
paper sluice
#

vouchbtn() you haven't passed the parameter data.

short silo
#

How to handle errors inside a cog ?

#

lib used : pycord

paper sluice
#

i think you can decorate your error handler with @<command_name>.error

short silo
#

also if its possible i would like to handle all the errors from the tree with a single function

naive briar
#

What's not working about it

short silo
naive briar
#

Pycord has trees?

short silo
ivory geode
#

Hey there,
having some problems getting started with slash commands:
Do I have to sync anything?
What am I missing?


import discord
from discord import app_commands
from discord.ext import commands

class ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print("Cog-Loaded: Ping")


    @app_commands.command(name="ping", description="returns the measured latency")
    async def pong(self, interaction: discord.Interaction):
        await interaction.response.send_message("Pong!")

# Setup function
async def setup(bot):
    await bot.add_cog(ping(bot))```
vocal snow
#

Where is the slash command?

ivory geode
#

oh hold on

glad cradle
hazy vault
#

Guys I need help
When I type the bot command, it doesn't work

glad cradle
tall temple
#

how can i get inviter in a on_member_join(member) event ?

hazy vault
glad cradle
tall temple
hazy vault
#

No, I don't know anything about this event

short silo
#

How to make a cog guild only ?

#

Its a listener.

hazy vault
#

@glad cradle

glad cradle
#

hey

#

is it a prefix command?

hazy vault
#

yes

glad cradle
glad cradle
hazy vault
#

k np

short silo
hazy vault
#

I put it here or send it to you in private @glad cradle

glad cradle
#

wait how was it

#

!d discord.ext.commands.Cog.cog_check

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
glad cradle
#

this

glad cradle
#

remove your token

hazy vault
#

k

short silo
hazy vault
#

import discord
from discord.ext import commands
from PIL import Image, ImageDraw, ImageFont
import requests # ุฅุถุงูุฉ ู‡ุฐุง ุงู„ุณุทุฑ ู„ุงุณุชูŠุฑุงุฏ ุงู„ู…ูƒุชุจุฉ "requests"

intents = discord.Intents.default()
intents.members = True # ุชู…ูƒูŠู† ุงู„ุจูˆุช ู…ู† ู‚ุฑุงุกุฉ ู‚ุงุฆู…ุฉ ุงู„ุฃุนุถุงุก ููŠ ุงู„ุฎุงุฏู…

ุชู… ุงุฎุชุตุงุฑ ุงู„ูƒูˆุฏ ู„ู„ุชุฑูƒูŠุฒ ุนู„ู‰ ุงู„ุฌุฒุก ุงู„ู…ุญุชูˆูŠ ุนู„ู‰ ุงู„ุฎุทุฃ

client = commands.Bot(command_prefix='$', intents=intents)

ุงู„ุฃู…ุฑ ุงู„ุฌุฏูŠุฏ

@client.command(help="Draw text on your profile picture.")
async def draw(ctx, text):
# ุชุญู…ูŠู„ ุงู„ุตูˆุฑุฉ ุงู„ุดุฎุตูŠุฉ
avatar_url = ctx.author.avatar_url
avatar_image = Image.open(requests.get(avatar_url, stream=True).raw).convert('RGBA')

# ุฅุถุงูุฉ ุงู„ู†ุต ุนู„ู‰ ุงู„ุตูˆุฑุฉ
draw = ImageDraw.Draw(avatar_image)
font = ImageFont.truetype('arial.ttf', size=32)
draw.text((50, 50), text, fill=(255, 255, 255, 255), font=font)

# ุชุญูˆูŠู„ ุงู„ุตูˆุฑุฉ ุฅู„ู‰ ู…ู„ู ูˆุฅุฑุณุงู„ู‡ุง ุนู„ู‰ Discord
avatar_image.save('edited_avatar.png')
await ctx.send(file=discord.File('edited_avatar.png'))

client.run('token')

glad cradle
glad cradle
#

enable it doing intents.message_content = True after intents.members

glad cradle
#

maybe you need to explicitly specify the path to the ffmpeg exe

short silo
glad cradle
#

try enabling logging to see if something unexpected occurs

glad cradle
slate swan
#

guys I just read the docs and in that I got to know there are two different commands

commands.Bot and the other is discord.Client
I just wanted to know how I can combine both of them

glad cradle
sick birch
#

commands.Bot is a superset of discord.Client so bot has everything client does and more

slate swan
#

Ohh I got it

#

thanks for the help ๐Ÿ™‚

glad cradle
#

mh could you share the full logs

#

there's an exception

#

send it

#

and could you also share the affected code?

slate swan
#
class PersistentViewBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def setup_hook(self) -> None:
        self.add_view(PersistentView())

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

can i use persistent button without doing this?

#

cuz my Persistentview() requires an arguement

glad cradle
#

mh is the YouTube link valid?

weak kite
#

what's the best practice for storing a bot token for discord.py

maiden fable
#

GOod question

#

store the unix timestamp as a real date, store the bot ID somewhere else, and store the discord encryption key part thingy somewhere safe, then fetch everything from all the places, do the stuff to make it a bot token and then use it

smoky sinew
#

doesn't even have to be a .env file

slate swan
#

how do i make it so only the author of the command can see the response

lament mesa
#

yeah, you can use a .py file too

lament mesa
maiden fable
#

use a bin file

weak kite
smoky sinew
maiden fable
lament mesa
vivid axle
#

how can i use a PIL.Image.Image as an image in discord.Embed im using dpy

vivid axle
#

i mean without saving the file? if thats possible

#

i think that requires a saved file

smoky sinew
#

it doesn't

vivid axle
#

ohh

#

ohhh

#

thanks

smoky sinew
slate swan
#

Guys How can I register slash commands in every server?

cloud dawn
#

Don't specify a guild

slate swan
#

i made a ticket system but i wanna add !close to close a ticket but idk how

#

can u help me?

#

i made a ticket system but i wanna add !close to close a ticket but idk how

#

yeah

#

but what if he writes it in another channel and deletes another chnnel?

#

i dont want code like that

#

yeah

#

Lemme send u my whole code

#
async def ticketcallback(interaction):
  guild = interaction.guild
  role = discord.utils.get(guild.roles, name ="interviews")
  overwrites = {
    guild.default_role: discord.PermissionOverwrite(view_channel=False),
    interaction.user: discord.PermissionOverwrite(view_channel=True),
    role: discord.PermissionOverwrite(view_channel=True)
  }

  select = Select(options=[
  discord.SelectOption(label="Help Ticket", value="01", emoji="โœ”๏ธ", description="This will open a help ticket"),
  discord.SelectOption(label="Application ticket", value="02", emoji="๐Ÿ“œ", description="This will open an application ticket")
])

  async def my_callback(interaction):
    if select.values[0] == "01":
      category = discord.utils.get(guild.categories, name="Tickets")
      channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrites)
      await interaction.response.send_message(f"Created ticket - <#{channel.id}>")
      await channel.send("Geia sas, pws mporw na sas boithisw?")
    elif select.values[0] == "02":
        category = discord.utils.get(guild.categories, name="Application tickets")
        channel = await guild.create_text_channel(f"{interaction.user.name}-ticket",          category=category, overwrites=overwrites)
        await interaction.response.send_message(f"Created ticket - <#{channel.id}>")
        await channel.send("Geia sas, pws mporw na sas boithisw?")

  select.callback = my_callback
  view = View(timeout=None)
  view.add_item(select)
  await interaction.response.send_message("Choose an option below", view=view, ephemeral = True)

@bot.command()
async def ticket(ctx):
  button = Button(label="๐ŸŽค Open a ticket", style=discord.ButtonStyle.green)
  button.callback = ticketcallback
  view = View(timeout=None)
  view.add_item(button)
  await ctx.send("Open a ticket below", view=view)
glad cradle
#

I'm not sure what's happening, can you try to use discord.FFmpegPCMAudio

slate swan
#

Do u understand the code @slate swan

glad cradle
#

yes

#

!d discord.FFmpegPCMAudio

unkempt canyonBOT
#

class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).

This launches a sub-process to a specific input file given.

Warning

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
glad cradle
#

wasn't you using FFmpegOpusAudio

slate swan
#

Snipy can y help me with aarav

glad cradle
#

hi what's the problem

slate swan
#

i made a ticket system but i wanna add !close to close a ticket but idk how

glad cradle
#

what are the options in FFMPEG_OPTIONS

#

pipe needs to be False

slate swan
#

Stop?

#

!close

#

I'll use !close

glad cradle
#

what audio source are you using? FFmpegPCMAudio or FFmpegOpusAudio?

glad cradle
#

you're passing them here

#

you don't need to pass them if their value is equal to the default ones

#

just leave url

slate swan
#

Will ya help me?

#

k

glad cradle
#

then Idk sorry

slate swan
#

lemme try it

#

oh i see

#

bc the code is a bit changed

#

lemme send u the updated one

#

!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
#

the whole code

tired kernel
#

can somone help me to make a count member whit cogs

slate swan
#

yeah

tired kernel
#

can somone help me to make a count member whit cogs

slate swan
#

which function

#

make the code i dont understand wdym

tired kernel
#

k

slate swan
#

where should i put this

#

alr lemme try

#

but the channel everytime changes

#

the channel is named based on the user's name

#

i know

#

but theres a different channel everytime

#

so the id changes

tired kernel
#

can somone help me to make a count member whit cogs

slate swan
#

didnt work

smoky sinew
#

bruh

#

don't make it global

shrewd fjord
#

Demn

smoky sinew
#

just save it to a database, this list won't save after the bot restarts anyway

shrewd fjord
#

Mudkip still here

vocal snow
smoky sinew
#

it is

#

look at the code

#

i juist haven't pushed it to git yet

vocal snow
#

ahh

shrewd fjord
#

Hm

slate swan
whole shoal
#

anyone knows how to reset the selection options before its called so you dont get

In components.0.components.0.options.5: The specified option value is already used

error

outer parcel
#

Im trying to make an interest command where for every single person in the database it adds on like 50 coins per hour

#

how would i create this hourly task

tall temple
#

that's easy

meager orchid
#

Hi guys, can you advise on the best way to handle permissions, cooldowns, and channels where commands can be used for a Discord bot? Should I use a database or some other method?

maiden fable
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
tall temple
#

@cloud dawn could you help me for that error ?

sick birch
#

You shouldn't need a database for it

meager orchid
#

As a beginner in programming, I am currently writing a bot on disnake, and I know that there are cooldowns and other features. But how can I make certain roles bypass the cooldowns set by the disnake library?

tall temple
meager orchid
cloud dawn
tall temple
#

what do i have to use ?

#

@cloud dawn

smoky sinew
unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
tall temple
smoky sinew
#

idk

#

probably the same

tall temple
smoky sinew
#

i do not know pycord sorry

tall temple
smoky sinew
#
class MyView(discord.ui.View):
    def __init__(self):
        self.add_item(discord.ui.Button(style=discord.ButtonStyle.link, url="https://example.com", label="Example"))

@app_commands.command()
async def slash_command(self) -> None:
    await interaction.response.send_message(view=MyView())
turbid canopy
#

oy

tall temple
smoky sinew
#

just make another class????

tall temple
smoky sinew
#

you cannot add two views

#

you're talking about adding two buttons

tall temple
#

yeah

#

that's what i mean HeheCat

smoky sinew
#

in that case you want add_item instead

lavish zephyr
#

Hello, does anyone ever managed to run a discord bot alongside a Flask app under Cpanel?

solar summit
#

I have, but not using cpanel

idle palm
#

@smoky sinew hey

#

do you know much about raspberry pi hosting

#

I know a bit about networking and i know i would need to setup a firewall and/or a proxie?

idle palm
solar summit
#

realistically, no.

idle palm
#

no what? no firewall or proxy?

solar summit
#

either

idle palm
#

oh why?

solar summit
#

why would you need it?

#

well, a reverse proxy can help improve the performance of your bot by caching frequently accessed data and load balancing incoming traffic

#

but realistically no ones going to try get gain unauthorized access to your bot

idle palm
#

idk if im correct but i thought a proxy is basically a middle man between the client and server (my pi)

solar summit
#

you are correct

idle palm
#

would my home network take care of dos attacks

#

and my pi wont need to worry

#

if there was any

solar summit
#

alsomexxx, no one can get your ip from your discord bot

idle palm
#

im not worried about that

#

im worried about people spamming useless requests to my bot

solar summit
#

but if you are worried about this, your typical home network will not take care of DOS attacks

idle palm
solar summit
# idle palm what will

okay, someone spamming your commands wont even be flagged by your network provider as it is coming from your own network

#

best course of action is to set up ratelimits if thats something you are really concerned about

idle palm
#

no im just curious sorry

#

im new to self hosting my bot

solar summit
#

no need to say sorry brother, here to help

idle palm
#

also, would 1gb of ram be alright

solar summit
#

I've had about 300 people spamming my bot during an event and while the bot sometimes slowed down my internet never did

solar summit
idle palm
#

what do you mean by small scale

#

how many frequent users

solar summit
#

hard to estimate but off of my experience, 4gb of ram it could handle anywhere between 1-2 commands a second

#

without a delay

#

what PI do you have? (i own the pi 4 b)

idle palm
#

2 b

#

I was on a budget

#

im using a wireless node and connecting a ethernet between that and my pi

solar summit
#

well, it will depend on various factors, such as the complexity of your bots commands, the number of users interacting with your bot, and the load on your raspberry pi's cpu and memory (if theres other stuff running on it)

idle palm
#

the bot will be the only use

#

i want to limit background processes

solar summit
#

the rasp pi 2b can handle (i would say) a moderate level of traffic for a simple Discord bot with basic commands. However, if your bot is handling a large number of commands per second or processing complex tasks, you may experience performance issues.

idle palm
#

yeah its not that big of a bot

#

only a couple commands i would say an hour

solar summit
#

then you should have no worries, i would suggest monitoring the work load on your cpu and memory while it is running

idle palm
#

it wont need any type of cooling would it?

solar summit
#

it'll most definitely get hot. person use with my Pi it reaches high degrees but you can buy a cheap fan if you're worried about it getting too hot

#

raspberry pi fans are fairly cheap

idle palm
#

Ok well thank you for helping

#

hopefully it all goes well when i set it up

solar summit
#

no worries, give me a ping if you need anything else!

idle palm
#

will do, thank you

solar summit
#

good luck

smoky sinew
#

what they said

#

only the discord api communicates with your bot

ornate crater
#

how to timestamp for embed?

maiden fable
#

datetime.datetime.utcnow()

ornate crater
#
embed = discord.Embed(description=f"{ctx.user} feldobta az รฉrmรฉt!", color=discord.Color.blue(), timestamp=datetime.datetime.utcnow())```
#

this?

#

@maiden fable

slate swan
#

yes

silk kestrel
#

how to fetch user banners because for me itโ€™s not working

smoky sinew
#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the userโ€™s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
smoky sinew
#

you need to do fetch_user first

slate swan
#

oh you gotta fetch the user itself

#

i thought it was just the banner

smoky sinew
#

@silk kestrel

silk kestrel
#

thank you

idle dune
#

Guys is there any glitch going on for discord.py and py-cord?

slate swan
#

no

#

do you face some issue?

outer parcel
#

I want to make a leaderboard but it only selects people in that server

#

how would i create this using aiosqlite

glad cradle
#

do you want to make a global leaderboard or a guild leaderboard

outer parcel
#

guild

#

global one i made

#

but guild one im strugglign with since how do i make it only extract data from people that are in the guild specified

glad cradle
#

then what's the problem

outer parcel
#

im struggling with making guild leaderboard

#

specific to people in that server

vocal snow
#

are you storing the user ids?

glad cradle
#

you already have the ids of the members that are in that guild

outer parcel
outer parcel
#

but how do i make it so instead of just getting top 10 people in the database

#

the people it orders are the people that are in the server

vocal snow
#

!d discord.Guild.members

unkempt canyonBOT
outer parcel
vocal snow
#

make a sequence of all the user ids in the server

outer parcel
#
users = [us.id for us in interaction.guild.members]
vocal snow
#

and just use a WHERE clause

outer parcel
#

so WHERE user = ?

vocal snow
#

IN

outer parcel
#

oh

#
users = [us.id for us in interaction.guild.members]
async with client.db.cursor() as cursor:
  await cursor.execute("SELECT money, user FROM banks WHERE user IN ? ORDER BY money DESC LIMIT 10",(users,))
#

so smt like this?

shrewd apex
analog current
#

"abc" + (f"type: {type.name}" if type is not None else "")

is this possible?

naive briar
#

What

plush oxide
#

f"abc type: {type.name if type else ''}"

shrewd apex
#

try

string = f"SELECT money, user FROM banks WHERE user IN {tuple(user)} ORDER BY money DESC LIMIT 10"
await cursor.execute(string)
smoky sinew
shrewd apex
#

i think injection might not be allowed with in operation like that

outer parcel
shrewd apex
#

it would be easier if there was a guild id column

outer parcel
#

i want data to be same across all servers

shrewd apex
outer parcel
outer parcel
#

GLobal one i made but server is difficult

smoky sinew
shrewd apex
#

remember that values need to be like this
user in (1, 2, 3, 4) order by

smoky sinew
#

oh you want to filter it for members that are in the current server

shrewd apex
#

also u could just do a for loop and match too i suppose but i think f string is a valid use case here

outer parcel
#

basically thats it

outer parcel
naive briar
#

Send the whole traceback

shrewd apex
#

print that statement once

naive briar
shrewd apex
#

i think tuple might be adding a extra comma or something which might make it an invalid statement

outer parcel
#

im prob dumb

#

but i think its tuple error

shrewd apex
#

what do u get when u print the statement

outer parcel
#

which statement?

shrewd apex
#

print the f string

outer parcel
#

also when i print the tuple

glad cradle
outer parcel
#

there is extra comma at end

vocal snow
#

better just make a table to map user id and guild id

shrewd apex
#

u cant inject at that position... unless u hack discord api

glad cradle
#

i said

shrewd apex
glad cradle
shrewd apex
#

pithink i assumed sarcasm

glad cradle
#

mad asher

shrewd apex
glad cradle
#

btw even if it's possible from a network perspective the library would error since it tries to convert discord ids to int

whole shoal
#
class Prot(discord.ui.View):
    response1=None
    list_result=[]
    self.users=users
    def __init__(self, users:list):
        super().__init__(timeout=10)
        
    
    async def selected(self, interaction:discord.Interaction, selected:discord.ui.Select):
    

How do i acesss the users list inside the selected function?
self.users?

naive briar
#

Doesn't exist, you didn't define it

whole shoal
#

oh

#

now?

naive briar
#

What

whole shoal
#

defined

lucid pilot
#

Hi guys! Trying to finish my discord bot. Is there now a way to add buttons to do specific commands like copy-to-clipboard the targeted text?

vale wing
lucid pilot
#

Or has there been a way now to use pyperclip with discord?

naive briar
#

What's that

#

!pypi pyperclip

unkempt canyonBOT
#

A cross-platform clipboard module for Python. (Only handles plain text for now.)

vale wing
naive briar
#

๐Ÿซ 

lucid pilot
vale wing
#

That's simple logic

#

How are you going to use clipboard of user's computer with your bot's server

#

There's no way unless you tell discord client to do so which you can't

lucid pilot
#

I've heard of using a headless browser to emulate user actions

#

Is that viable?

vale wing
vale wing
#

You cannot interact with user's computer, you can only send data to client (or to discord servers and then they send it to client) and it decides what to do with that

lucid pilot
#

I see, thanks for clarifying

#

๐Ÿฅน

slate swan
#

Can someone show me the examples of cogs in discord py v2

naive briar
#

It's exactly the same

#

Maybe just a little different that in v2 the add cog meth is async

#

But that's it

slow ether
#

Guys How Get Person Role In Discord Server In Discord bot like interactive.role?

slate swan
#

when i restart my bot my buttons doesnt work how to fix it?

#

hey guys so im making a discord bot with the package dhooks
and when i do @lament oaron'e it works as should but when i do @(role) it doesnt notify the people in the role it just types @(role)
code:
webhook.send("@premium")

vale wing
#

member.roles and member.top_role correspondingly

slow ether
#

so interactive.top_role?

vale wing
#

What is interactive

slow ether
#

ah the person

#

that did the command

vale wing
#

As far as it's an instance of discord.Member sure

outer parcel
vale wing
#

If this is your question (not sure why you submitted image tho) the solution is to have individual row for each user ID โ€” item ID pair

slate swan
#

how to make persistent button?

#

which decorator to use in cogs for creating a slash command

class UserProfile(commands.Cog):

    def __init__(self, bot: Bot) -> None:
        self.bot = bot
    
    //some decorator
    async def profile(self, interaction: discord.Interaction):

        await interaction.response.send_message('ok')
shrewd apex
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
shrewd apex
#

@slate swan

slate swan
tired pine
#

What should I make my bot do? ๐Ÿค”

steady flume
#

here i have id of players, how can i add this id to other class

slate swan
#

i don't understand the problem here

#

i did copy and past from website and put my own bot token

tall temple
vocal snow
tall temple
#

@default_permissions(administrator=True)

vocal snow
#

Ok but that's not part of discord

tall temple
#

it works in my hoster

vocal snow
#

Recheck it's location

tall temple
#

but not in replit bcz i'm outside

vocal snow
#

discord.default_permissions doesn't exist so it's not going to work anywhere

#

Check the docs, make sure it's part of discord and not discord.app_commands or something else

vocal snow
#

Which is causing an issue

#

Run the code via the py command instead of through the IDE

supple hawk
#

can anyone help me making a discord bot maybe 100- 200 lines of code only ๐Ÿ˜ญ๐Ÿ˜ญ๐Ÿ˜ญ๐Ÿค‘๐Ÿค‘๐Ÿค‘๐Ÿค‘

vocal snow
stuck crown
#

so i have the message intent enabled for my bot but im not receiving message.content... i am using this portion of code to test this

@client.event
async def on_message(message):
    if message.author == client.user:
        print(f'{message.channel.name} + {message.author.name} + {message.content}')
        return

    if message.content.startswith('$hello'):
        await message.channel.send(f'Hello {message.author.name}!')

    if message.content.startswith('$dead'):
        await message.channel.send(f'you died {message.author.name}!')
stuck crown
#

in the discord admin portal

#

dev portal*

vocal snow
#

You have to enable it in code too

stuck crown
#

yes there as well with this

#
intents.messages = True
intents.message_content = True
intents.typing = True```
vocal snow
#

And where are you using the intents variable

#

After defining this

stuck crown
#

that is a excellent question

#

where/how would i use the intents variables?

vocal snow
#

you pass it to intents kwarg of discord.Client

slate swan
#

what's the problem now ?