#discord-bots

1 messages Β· Page 342 of 1

cloud dawn
#

netcup

ancient raven
weak tendon
#

Typically cache is just a common data structure like dict or list, unless you're caching remote database

#

In that case you would use redis

severe sonnet
upbeat otter
#

You can easily store that in a dictionary

severe sonnet
#

yeah i read a doc from real python related to cache

upbeat otter
#

right

severe sonnet
#

seems like dicts works like cache in python

upbeat otter
#

kinda like that

#

you can use lists too but your use case..dictionaries are way easier to implement

severe sonnet
#

yeah

#

also how do i check if a user by their ID have admin permission of a guild by it's ID?

severe cove
#

@commands.has_permissions(administrator=True)

#

put it right after @bot.command()

#

this ensures that the specific command can only be used by an admin

severe sonnet
#

i'm not doing it in bot, but in a custom library i'm making for macros

#

so @commands.has_permission won't work for me

#

as you can see, here i have a cache with the guild id and user id

#

i need to use the guild id to gather the guild as an object

#

then verify the user permission using their id

somber sky
#

the most i got to was command_count = len(client.commands) which does the regular commands but not the tree commands and if i do command_count = len(client.tree.commands) then it dont work

slate swan
#
        for p in pathlib.Path("./modules").glob("**/*.py"):
            p.load_extension(p.as_posix()[:-3].replace("/", "."))
            self.load_extension(f"modules.{module[:-3]}")```

```    p.load_extension(p.as_posix()[:-3].replace("/", "."))
    ^^^^^^^^^^^^^^^^
AttributeError: 'WindowsPath' object has no attribute 'load_extension'```
weak tendon
#

Put the arg into self.load_extension

slate swan
weak tendon
#

This seems like your imports organisation issue

#

Could you share file hierarchy

unique geyser
#

how do I send a message in a specific channel in a specific server?

severe sonnet
#

how do i check if a member have a certain guild permission, in my case admin perm?

#

like, this command only returns the guild permissions, but i have no idea how to check a certain permission

#

member.guild_permission()

somber sky
#

len(client.commands) how do i do this but with tree commands?

midnight oracle
unique geyser
midnight oracle
midnight oracle
# severe sonnet `member.guild_permission()`

If you want to check for the specific "Admin" role you could use the has_role method or just use the memeber.guild_permission.administrator to check if the user has admin permissions

unique geyser
midnight oracle
unique geyser
#

alright

naive briar
#

And for the command count of both prefix and app comands, you can just add them together

dusk shadow
#

what type of command is used for feedback?

(like the popup type, where you can enter information in a text box)
i think ive seen it somewhere, but i dont quite remember where.

naive briar
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
dusk shadow
#

and...
to send any of the information to an entry?
where would any of this data go if someone were to add an entry?

i was looking at the example on the Github, and i see all it does is pop up, but any of the data just, goes nowhere...
i would assume that i would need to throw the response to a file, or some sort of DM at that point...
the example is like a suggestion box, but the suggestions just go to a paper shredder.

naive briar
golden portal
#

its jus textinput.value

naive briar
#

Oh right

#

Did they change it?

golden portal
#

nop always been this way

#

u confused with select probably

naive briar
#

That's weird 🫀

golden portal
#

na its more ergonomic tbh

#
class MyModal(ui.Modal):
    bob = ui.TextInput(label="bob")
    async def on_submit(self, interaction):
        await interaction.response.send_message(f'u set bob as "{self.bob=}"')
dusk shadow
#

so, but thats just.
oh....

golden portal
#

flowery

dusk shadow
#

so, essentually i need to make it so {self.bob=} is on another await, where i can have the bot ether write to a file, or dm me?

golden portal
#

sure

#

just do self.bob.value to get the actual value

dusk shadow
#

So, i took this from the Github... what im after, is taking essentially the response from the feedback portion of the code, right?

class Feedback(discord.ui.Modal, title='Feedback'):
    # Our modal classes MUST subclass `discord.ui.Modal`,
    # but the title can be whatever you want.

    # This is a longer, paragraph style input, where user can submit feedback
    # Unlike the name, it is not required. If filled out, however, it will
    # only accept a maximum of 300 characters, as denoted by the
    # `max_length=300` kwarg.
    feedback = discord.ui.TextInput(
        label='What do you think of our Slash Commands?',
        style=discord.TextStyle.long,
        placeholder='Type your let us know here...',
        required=False,
        max_length=400,
    )

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}! I have let `nalathethird`, my creator, know what you think of me!', ephemeral=True)
    async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
        await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)

        # Make sure we know what the error actually is
        traceback.print_exception(type(error), error, error.__traceback__)
#

so, i would do something along the lines of,
await interaction.response.send_message(self.feedback.value)
to uhhh... a guild channel?

naive briar
dusk shadow
#

essentially, yea...
maybe in embed format?

id rather it come directly to me, as im the only one coding it, but i could throw it into our genchat for admins only.
guess i could also make it almost a way for members to report a user as well if they are breaking rules, TOS, or anything like that

somber sky
stable girder
#

Hi guys, made a bot for discord and when I give the command my bot doesn't send any messages in the chat. I programmed it so that when I tag him in chat he sends a message and he sends that message, but when I give a command the bot doesn't show any signs of life.

midnight oracle
stable girder
vague matrix
hushed juniper
#

py-cord unxpected keyword url

stable girder
vague matrix
#

Yeah

#

Don't send it in a file

stable girder
#

the code is too big

vague matrix
#

send the command then

stable girder
vague matrix
#

is that the full codebase?

stable girder
#

yeah

vague matrix
#

bot.run(token)

#

put that at the end of your script

stable girder
#

token and prefix are in config.json

#

First I did it the way you said and it didn't solve my problem either.

vague matrix
#

Because you have no token in the script?

#

The script needs to load the token or else it won't work

stable girder
#

but the script had a token, the bot still didn't send a message in the same way

vague matrix
#

You don't even have import json in the script so how are you loading the token

stable girder
#

Oh my god, I sent the wrong code, I'm sorry

midnight oracle
midnight oracle
naive briar
somber sky
hushed juniper
#

Someone help

somber sky
somber sky
desert kiln
#

Question, can custom emojis be used in slash command descriptions?

naive briar
#

No

civic reef
#

can anyone tell what is error here? Keyerror? How should I resolve it?

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

exotic island
civic reef
#

does anyone know how to host a discord bot free?

#

@exotic island what is view work?

civic reef
#

features

#

working

weak tendon
#

Or trial periods on amazon aws, ms azure, digital ocean

civic reef
#

okay

exotic island
upbeat otter
civic reef
#

πŸ‘€

naive briar
young dagger
#

Or you just pay 5$ month and get a proper vps

civic reef
#

true

#

thanks all

upbeat otter
young dagger
#

It's going to be one less pizza for you

upbeat otter
#

I'm broke to afford that too

weak tendon
young dagger
upbeat otter
#

yeah

red blade
#

With a group like this, is it possible to have a sub-group in a group so the command could be something like stats user info

import discord
from discord.ext import commands
import datetime

class Stats(commands.Cog):
    def __init__(self, bot):
        self.bot = bot 
    
    stats = discord.app_commands.Group(name='stats', description='All commands related to statistics.')


    @stats.command(name = 'member-count', description = 'Gives the amount of members in the server')
    async def member_count(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Server Member Count: {interaction.guild.member_count}")

    @stats.command(name = 'user-info', description = 'Gets information about a certain user.')
    async def user_info(self, interaction: discord.Interaction, member: discord.Member = None):
        member = member or interaction.guild.get_member(interaction.user.id)
        embed = discord.Embed(title = "User Info").set_author(name = member.name, icon_url = member.avatar.url if member.avatar is not None else "")
        embed.add_field(name = "Created At", value = f"<t:{int(member.created_at.replace(tzinfo=datetime.timezone.utc).timestamp())}:F>", inline = False)
        embed.add_field(name = "Joined At", value = f"<t:{int(member.joined_at.replace(tzinfo=datetime.timezone.utc).timestamp())}:F>", inline = False)


        await interaction.response.send_message(embed = embed)


async def setup(bot):
    await bot.add_cog(Stats(bot))
weak tendon
red blade
#

lirc?

weak tendon
#

Google?

red blade
#

i couldnt find it

weak tendon
red blade
#

oh

red blade
#

is there an event for when a button is pressed?

shrewd fjord
#

if disnake yes, if discord.py then use on_interaction

#

!d disnake.on_button_click

unkempt canyonBOT
shrewd fjord
#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.

New in version 2.0.
red blade
#

oh thanks

severe sonnet
#

okay so, do Message discord object have guilds?

#

i need to gather guild id from discord.Message

golden portal
#

!d discord.Message.guild

unkempt canyonBOT
severe sonnet
#

how do i send discord message from my bot using discord.Message?
cus i'm using listener

golden portal
#

what does that have to do with sending messages

runic void
#

He guys, I encounter an issue with discord bot created with python. I try to make a form application with the discord.ui module.
I pop ups nicely but clicking on the button to submit nothing in the error logs console. just on discord message something happends try again later.

class ApplicationModal(Modal):
    def __init__(self):
        super().__init__(title="Guild Application")

        self.add_item(TextInput(label="What is your ingame name?", custom_id="ingame_name"))
        self.add_item(TextInput(label="What is your motivation to join us?", custom_id="motivation", style=discord.TextStyle.long))
        self.add_item(TextInput(label="What legacy level are you?", custom_id="legacy_level"))
        self.add_item(TextInput(label="What is your gameplay time a week?", custom_id="playtime"))
        self.add_item(TextInput(label="What gameplay do you like the most to play?", custom_id="favorite_gameplay", style=discord.TextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        try:
            # Create an embed with the user's responses
            embed = discord.Embed(title="New Application", color=discord.Color.blue())
            for item in self.children:
                embed.add_field(name=item.label, value=item.value, inline=False)

            # Fetch the channel where the results should be sent
            results_channel = await bot.fetch_channel(results_channel_id)
            
            # Send the embed with the application results to the channel
            await results_channel.send(embed=embed)
            
            # Respond to the user's interaction confirming the application was received
            await interaction.response.send_message("Thank you for your application!", ephemeral=True)

        except Exception as e:
            # If anything goes wrong, log the error
            print("Failed to send application result: {}".format(str(e)))
            
            # Send a follow-up message to the user if the initial response has already been sent
            await interaction.followup.send("There was an issue with your application. Please contact the server admin.", ephemeral=True)

class ApplicationButtonView(View):
    @discord.ui.button(label="Start Application", style=discord.ButtonStyle.green, custom_id="start_application")
    async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_modal(ApplicationModal())
golden portal
#

!d discord.ui.Modal.on_submit

unkempt canyonBOT
#

await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Called when the modal is submitted.
golden portal
runic void
#

Thanks I'll have a look!

runic void
golden portal
#

oki

clever spade
#

anyone have a ticket bot code

near sail
midnight oracle
midnight oracle
clever spade
vapid parcel
#

I have a question, I have made logs inside of my bot, but im trying to make it use webhooks, I got that part down.. but for each event would I actually have to make a webhook for each event..? Or how can I make it like check for multiple webhooks or something.. im just confused on how I could do this..

#

Because each event can have their own channel... is what im saying, which there are 19 events

sick birch
vapid parcel
sick birch
#

you should do that. if that's not possible it's fine to send all logs to one channel

vapid parcel
#

Its like this, but then you click on message events, and it will have multiple options

sick birch
#

but really you should be using log aggregation software (which discord is not)

vapid parcel
#

wdym?

#

I just use discords logging system(using their events basically)

sick birch
#

ah these aren't logs related to your bot

vapid parcel
#

no no

sick birch
#

i mean, you still could use log aggregation software

#

it would give better statistics

#

but most bots just send these in webhooks

vapid parcel
#

yes

#

but, im wondering how to store all 19 webhooks or something?

#

because you would have to store the webhook if im not wrong?

sick birch
#

19 webhooks? why not just one?

vapid parcel
#

Because each event can have their own channel

#

thats why I came in here to ask...

sick birch
#

19 channels does not seem ideal

#

but if you wanted to do that yes you would have to store them. put them in a database for instance

vapid parcel
#

hm

flat pier
#

would each webhook have their own name and stuff?

vapid parcel
#

Nah ^

#

Im just trying to think, cuz some idiots like to have there stuff seperated in like multiple things... but personally I just have 1 channel for all logs.. so this issue wouldn't be for me, but some people are weird, so im just trying to think the best way to do tho..

#

Wait, i could add a button where it will say, Message Events Channel, then all 4 will go there, you enable or disabled it using yes or no maybe. Then I could just use 4 webhooks like Robin said

sick birch
#

allow customization. i think the default option of 4 channels for what you've sent in that screenshot is good, but also add an option for people to set custom channels on an event by event basis

vapid parcel
#

Im thinking of just having a button for the channel, but the button for now will just toggle on or off maybe? Then it will ask what channel when you click the channel button, or something, then those events will use that webhook

#

meaning max 4 webhooks

#

Like changing these buttons to Disabled or Enabled, then have a button named {eventname} Log Channel, they click it, then they just send what channel, when you enter that channel, it will create the webhook then. Then it will store that webhook, using max 4 webhooks like robin mentioned..

#

which will require a whole rework on my logs lol

quick gust
#

what I would do is have 4 categories like u do, and then 4 webhooks (4 channels) and all the events inside each category will be enabled by default but users can disable/re-enable specific events or even the whole category.

somber sky
#

len(client.commands) how do i do this but with tree commands?

vapid parcel
#

this isnt done, but an example of what I have done so far.

vapid parcel
#

@quick gust(sorry for ping)

Basically this is my idea so far, which is kinda working really well some how. But if a webhook is deleted, it will make a new one.

Video:

naive briar
#

There's no such thing as a tree.commands (discord.app_commands.CommandTree.commands)

quick gust
vapid parcel
#

Which I think is going pretty well so far now.

quick gust
#

Oh I see

#

yeah looks like it works well from that video

vapid parcel
#

Yeah

#

only 1 part 😭

#

Still gotta do everything else obvi.

quick gust
#

right right

midnight oracle
#

Sorry, my bad

somber sky
#

len(client.commands) how do i do this but with tree commands?

pulsar bridge
#

How'd I use an art asset for a rich presence game activity?
I tried

act = disnake.Activity(
    name=";help",
    state="x",
    details="x",
    assets= {
        "large_image":"key1", 
        "large_text":"text1",
        "small_image":"key1",
        "small_text":"text2"
    },
    type=disnake.ActivityType.playing,
)

but it doesnt show the assets or the details
(Using disnake, following this page: https://docs.disnake.dev/en/stable/api/activities.html#activity)

vapid parcel
pulsar bridge
#

Oh, I didn't realize there was an official -- many thanks

vapid parcel
#

Np

slate swan
#

Hello, I am needing assistance in this bot, the language is in python and it is called a verification bot

someone has paid me $5 to make this bot work and give it to them and i am somewhat new to coding

what this bot does apparently is when you verify with it through a qr code, it will send a custom message everywhere possible,

I have got it running before but was stuck on the qr code part, if someone can help me please do so

runic void
golden portal
quick gust
#

what does "doesnt work" mean

clever spade
#

I need a ticket bot, anyone have one?

drifting arrow
#

I got ones tailored towards the game rust if u want

#

it's here somewhere.

clever spade
drifting arrow
#

Aight

robust gull
#

where am i supposed to put the file? im terribly new sorry

drifting arrow
#

no such file or directory

robust gull
#

would it have anything to do with the version

shadow vigil
shadow vigil
#

I am not sure where is the desktop in macos

#

but it could be called desktop

#

use cd desktop

robust gull
#

man im so lost

#

i just want to use a bot that makes videos for me

#

could you be so kind as to type out the commmand to run the file if its on my desktop

#

wait it says permission denied now lol

slate swan
#

Hello, I am needing assistance in this bot, the language is in python and it is called a verification bot

someone has paid me $5 to make this bot work and give it to them and i am somewhat new to coding

what this bot does apparently is when you verify with it through a qr code, it will send a custom message everywhere possible,

I have got it running before but was stuck on the qr code part, if someone can help me please do so

IF THIS BOT IS MALICIOUS PLEASE TELL ME

twilit grotto
twilit grotto
twilit grotto
robust gull
#

thank you

twilit grotto
robust gull
#

no

#

i just tried it now

twilit grotto
#

do the * after 777

robust gull
#

so chmod 777* then ./main.py

clever spade
twilit grotto
#

lmk if that doesn't work

slate swan
#

i just wanted to get it working because i was paid, and the guy said he would pay me more if i could help him get other bots working

vapid parcel
vapid parcel
vapid parcel
clever spade
# vapid parcel np lmao

every single one i have seen is .js, and i dont know js so even when they tell me wht to edit i fail

vapid parcel
#

I did get it from another person, but I made it like 10x better because they person who gave it to me, he made it for 1 ticket only, i made my have unlimited amount of tickets, you just gotta know what you are doing I guess lol

vapid parcel
#

Theirs was lowkey ass, so I made theirs better, but its not the best ticket system, but it works lmao

robust gull
vapid parcel
#

Does buttons n everything, on startup it loads the old buttons so you don't have to re run the ticket command to get the embed up

clever spade
vapid parcel
clever spade
vapid parcel
#

you are supposed to just run main.py

#

make sure you put in your token too

clever spade
#

wait lemme get vs code rq

vapid parcel
#

I use pycharm, but vs code will work too

clever spade
vapid parcel
#

just another ide based on python only

#

vs code is for other languages including py.

vapid parcel
#

discord.errors.LoginFailure: Improper token has been passed.

#

it shows the errror...

clever spade
#

oh lol

clever spade
vapid parcel
#

then define it?

clever spade
#

yk where it is

vapid parcel
#

.......

#

Bro, replace roleid with the fucking role id

#

Like what? 😭

#

if you read what the important notes say, you would know this...

clever spade
#

Where has it been used 😭

vapid parcel
#

bro does not know python GoofySkull

clever spade
#

oh shit

#

mb

clever spade
#

@vapid parcel i have failed

vapid parcel
#

I can tell

#

but I have no time to help you. I have to update other things on my end, if you can read basic instructions then you will know how to make it work.

#

I currently have that exact source running on my server. and multiple other servers. So its not the source, its just you man.

clever spade
# vapid parcel I currently have that exact source running on my server. and multiple other serv...

PS C:\Users\mr_fa\Downloads\TicketSystem-main> & C:/Users/mr_fa/AppData/Local/Programs/Python/Python311/python.exe c:/Users/mr_fa/Downloads/TicketSystem-main/TicketSystem-main/main.py
2024-02-17 22:33:52 INFO discord.client logging in using static token
SFRU Tickets Bot has logged in successfully.
Everything has been loaded.
Bot_Admin has been loaded.
Error_Handling has been loaded.
Ticket Buttons added!
2024-02-17 22:33:54 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 5b53b6bb5305fbbf0cf2d826f84cca1c).
SFRU Tickets Bot is ready to recieve commands.

#

fixd

vapid parcel
#

kk

clever spade
vapid parcel
#

both work.

#

its hybrid(the best ever)

clever spade
#

ok ima go test it

vapid parcel
#

Why only have slash commands? Why only have prefix? Have both, HYBRID!!

vapid parcel
clever spade
#

!

clever spade
vapid parcel
#

?

clever spade
vapid parcel
#

Bro, just simply read what I have said on the repo

#

im not gonna help you with something really simple...

clever spade
somber sky
#

len(client.commands) how do i do this but with tree commands?

vapid parcel
somber sky
shadow vigil
#

hello

#

I was trying to fix a problem in nextcord. trying to create a kick command


@commands.has_permissions(kick_members=True)
@client.slash_command(description="Kick a member", guild_ids=[TESTING_GUILD_ID])
async def kick(interaction: Interaction, member: nextcord.Member, reason: str = "No reason provided"):
    await member.kick(reason=reason)
    await interaction.send(f"{member.display_name} has been kicked.")
#

but seems like its not working, anyone with or not with the kick permission can kick

#

I saw this Note that this check operates on the current channel permissions, not the guild wide permissions. in the docs

#

could be the reason?

sick birch
#

I understand your frustration but you don't have to take it out on them

somber sky
#

if it was a regular prefix command then it would be interaction.send

shadow vigil
somber sky
#

its supposed to be after the command

#
@client.slash_command(description="Kick a member", guild_ids=[TESTING_GUILD_ID])
@commands.has_permissions(kick_members=True)```
shadow vigil
somber sky
#

you cant make permissions before the command is made

shadow vigil
#

the reason it was before, its because it didn't work

#

so I tried that

somber sky
#

probably @commands.checks.has_permissions(kick_members=True)

#

wait

#

i sent the same thing oops lol

#

i just realized you are using nextcord

#

idk how to use nextcord at all

shadow vigil
#

that how I fixed my problem

vapid parcel
#

How many requests can webhooks have per second?

Bots get 50 per second, im guessing 50 per second for webhooks too?

sick birch
vapid parcel
vapid parcel
vapid parcel
velvet temple
#

anyone know this this isnt hiding it like it's supposed to
like ||GatosT001||

naive briar
#

Is it in a field's name? If yes, markdowns are not supported there

civic reef
#

What if someone get to know about my discord bot's token? It will steal my data? Is it harmful to me?

naive briar
#

They just get to run the bot and do pretty much everything you can do with it (except for the app settings)

shrewd fjord
#

Anyone knows the value of
discord.Intents.all(), as in integer

naive briar
unkempt canyonBOT
#

The raw value. You should query flags via the properties rather than using this raw value.

shrewd fjord
naive briar
#

You can look at the Discord docs, they have a section explaining on how to calculate it

golden portal
#

!e ```py
print(bin(1 << 15 | 1 << 14))
print(1 << 15 | 1 << 14)

unkempt canyonBOT
#

@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 0b1100000000000000
002 | 49152
shrewd fjord
#

Oh lol, gotta look at docs thankie

raw jacinth
#

Does anyone know how I can have to fields in each row?

#
        embed.add_field(name="Level", value=profile['level'], inline=True)
        embed.add_field(name="XP", value=profile['xp'])
        embed.add_field(name="Wallet", value=profile['wallet'], inline=False)
        embed.add_field(name="Bank", value=profile['bank'], inline=True)```
#

I want it Level XP Wallet Bank

quick gust
#

try removing inline=True from Bank

raw jacinth
#

The inline=Falsein Wallet causes anything after to go to the next one. But if I do inline=False in XP then it'll cause XP to not be in the same line as Level

slate swan
#

but (practically) you can create an empty field with invisible characters

covert bramble
#

guys i have a question im tryin to make a ban command on my discord bot but it isnt workin

@bot.command()
@commands.has_role("Owner/Mod")  # Import has_role
async def ban(ctx, member: discord.Member, *, reason):
    if reason is None:
        reason = f"This user was banned by {ctx.message.author.name}"
    await member.ban(reason=reason)
#

did i do something wrong?

#

cuz it isnt workin when i try the command

slate swan
#

Intents enabled? Do you have the role?

covert bramble
#

i do have th role

#

and i do have intents enabled

slate swan
#

Which ones

covert bramble
#

at the top

#

i have all of them enabled i think

slate swan
#

The @bot.command() decorator goes below the role check btw

covert bramble
#

can u wrtie an example

#

of how im supposed to write

slate swan
#

... for real?

#

I just said it goes before.. switching two lines shouldn't be that complicated..

covert bramble
#

bro i js started coding

#

i learned the bascics of python

#

but im still new to coding in general

slate swan
#

I said. Switching. Two lines...

covert bramble
#

i get it now

#

so this should work?

waxen vapor
#

how do you host these discord bots?

slate swan
#

VPS, paid

dense inlet
#

Unsure of how though

covert bramble
long pecan
#

Heya, Would the .has_role() work with say 2 roles?

slate swan
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
slate swan
long pecan
#

There it is!
I was looking for this guide for so long. ❀️

slate swan
long pecan
#

While you're here.
Can I intercept this MissingRole error and do something else instead?

slate swan
#

you mean you want to raise your own error?

long pecan
#

Not even to be honest.
More like:
@commands.has_any_role()
if not: do something else

slate swan
#

you can, but not with the decorator

long pecan
#

Also, im confused now.
@bot.command() @commands.has_role("x")
<- as per your guide.

#discord-bots message But this has it the other way around?

slate swan
#

you would have to check if user has roles inside the command and then you get to use if statements

long pecan
#

Okay, not the end of the world πŸ™‚
Im still exploring what's possible and what's not

slate swan
#

Im thinking of a thing that will auto press a button and flush the toilet. can anyone help me?

#

a discord bot

#

it will be

#

first I was thinking to be with a command /flushtoilet but no

#

a camera should be attached

slate swan
#

and it will somehow determine if it needs to press the button now

#

When I'm done

#

like that google ai

#

u watched it ?

long pecan
slate swan
long pecan
#

Now, last thing.
I'm passing in a set to the has any roles. should I make it a tuple instead?
cz as of now it's not working πŸ˜› But maybe I must do the snowflake thing? (still need to learn about that)

slate swan
#

it doesnt take set nor tuple

#

it takes x amount of arguments

#

.has_any_roles(123, 456, 789)

#

so you can do py roles = {1, 2, 3} @has_any_roles(*roles)

long pecan
#

Ah. *

slate swan
#

!e py print(*{1, 2, 3})

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

1 2 3
slate swan
#

yup you can do that

long pecan
#

yeah I know.
But if you forget it doesnt work πŸ˜›

#

Works now πŸ™‚ Thanks

long pecan
#

does the @commands.has_any_role() still work above that?
If I have a
@commands.has_any_role()
@app_commands()

slate summit
#

does anybody know how to get the last message that a user sent in the current channel?

#

about discord bots

slate swan
#

Get the channel object and loop through the message history, and check the user IDs

slate summit
#

bruh im never asking gemini to generate code again

#

everything is giving errors ill just do it myself

slate summit
#

i started coding discord bots yesterday so i dont know much

slate swan
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.

Examples

Usage...
slate swan
#

!d discord.ext.commands.Context.channel

unkempt canyonBOT
slate summit
#

hmm

#

also where can i find a list of commands/functions or stuff like "message.content"/"message.send"

quick gust
#

under the attributes and methods of the Message object

#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
quick gust
slate summit
slate summit
quick gust
long pecan
#

Hey,

Im looking to send a message to a specific channel when bot is online. (Same as lancebot has to dev-log for instance.)
However I'm struggling to see where to put this message or how to implement this.
I tried at the end of setup_hook but get_guild() returns None and therefor get channels returns None. Any suggestions?

shrewd apex
#

!d discord.ext.commands.Bot.fetch_guild

unkempt canyonBOT
#

await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity) and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice) per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member).

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_guild) instead...
shrewd apex
#
server = bot.get_guild(id) or await bot.fetch_guild(id)

also bot also has a get_channel and fetch_channel methods so if u have the channel id ur good to go

quick gust
#

yo asher

shrewd apex
#

hello πŸ‘‹

quick gust
#

I have a command that has a pretty long cooldown (10 hours) after its invoked once. but it also has the possibility to error (if the user isnt registered to the bot).

i was thinking of using before_invoke to see if they are registered or not, but im not entirely sure how to use it. you got an example?
(im using disnake)

shrewd fjord
shrewd fjord
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

shrewd fjord
#

What?

quick gust
shrewd apex
#

why not reset the cooldown of the command if say the command was invoked but an error other than cooldownerror occurred u can check in the error handler for a specific error using isinstance and if in this case say its not registered exception then reset the cooldown

shrewd fjord
quick gust
shrewd fjord
#

But for app commands it should be the same, cause app commands cool downs are managed by libs too

shrewd apex
#
async def on_slash_command_error(
        self, inter: disnake.ApplicationCommandInteraction, error: commands.CommandError
    ) -> None:
        if not isinstance(error, commands.CommandOnCooldown):
            inter.application_command.reset_cooldown(inter)
#

here is an example

long pecan
shrewd apex
#

run it in on_ready with a flag variable of some sorts or u can have it as a one time task using tasks.loop and bot.wait_until_ready()

#

bot needs to start before actually being able to send a message

#

count seems appropriate for this

shrewd apex
#

πŸ‘

shrewd apex
long pecan
#

like this?

self.onready_ran = False
if not self.onready_ran:
    # send embed
    self.onready_ran = not self.onready_ran
shrewd apex
#

the initial value

long pecan
#

yeah. Got it underneath self.synced in the init

shrewd apex
#

yeah

glad cradle
#

mh

#

just subclass the bot class and edit the start method behaviour πŸ˜”πŸ€™

clever spade
#

anyone know how to fix this

#

2024-02-18 21:43:51 ERROR discord.ui.view Ignoring exception in view <ticket_launcher timeout=None children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='β€’ Support' emoji=<PartialEmoji animated=False name='πŸ‘·' id=None> row=None>
Traceback (most recent call last):
File "C:\Users\mr_fa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "c:\Users\mr_fa\Downloads\TicketSystem-main\TicketSystem-main\views\buttons.py", line 25, in ticket
return await interaction.response.send_message(f"Ticket category '{ticket_category_name}' not found!",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\mr_fa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 774, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

naive briar
#

Don't respond to an interaction twice with interaction.response

slate summit
#

also what are you making your bot do

#

im lost on ideas

slate swan
#

on_ready can be called multiple
times, also not sure but get_channel
might return None when it's not
cached so eventually you could fetch
the channel I guess pithink

errant hill
#

Hi

unkempt canyonBOT
#

bot%2Fexts%2Futilities%2Flogging.py lines 19 to 21

await self.bot.log_to_dev_log(
    title=self.bot.name,
    details="Connected!",```
`bot%2Fbot.py` line 41
```py
async def log_to_dev_log(self, title: str, details: str | None = None, *, icon: str | None = None) -> None:```
pale zenith
#

%2F

pliant minnow
vapid parcel
#

anyone have a twitch n youtube notification working in dpy?

#

or how to set one up maybe?

merry cliff
#

I have a really scuffed twitch one

vapid parcel
#

uses dpy?

merry cliff
#

Not sure about YT tho

#

Ye

vapid parcel
#

yeah if it works, then ill take it lol

#

i can fix it up dw 😭. I just can't find a WORKING one... and I kinda just don't wanna go through the pain of having to actually get one working...

merry cliff
#

Ok just letting u know I made it 2 years ago before I learned how to use databases so it stores all the stuff in a json file

vapid parcel
#

thats fine

#

I know how to use databases xD

merry cliff
#

There’s a twitch cog in there

#

Good luck

vapid parcel
#

ty

#

if you find a yt one, please let me know!

merry cliff
#

Ok

#

Uhh is your game activity allowed lol

vapid parcel
#

yes if its not the real thing.

merry cliff
#

Ok

vapid parcel
#

which it clearly isnt 😭

merry cliff
#

Oke

wraith canopy
#

Hi

merry cliff
#

Hello

wraith canopy
#

What are you capable of doing

merry cliff
#

Wdym

weak tendon
#

What the

    for number in range(1, 9999999999999999999999999999999):```
craggy lark
craggy lark
weak tendon
#

And I highly suspect that "autofarmer" is something that violates ToS thereby you can't expect help on it

craggy lark
#

Okay

torn solar
#

why wont my slash command show up even though command tree is synced 😭

weak tendon
long pecan
long pecan
#

Perfect:)
Also, pro tip, (learn from my mistakes lol)
If you spam sync to get it to show up you’ll get rate limited πŸ‘πŸ»

latent veldt
#
    @commands.is_owner()
    @cog_ext.cog_slash(name="admin", description="Admin Commands")
    async def admin_group(self, ctx: SlashContext):
        await ctx.send_help(ctx.command)

    #subcommands
    @admin_group.sub_command(name="load", description="Load a Cog")
    async def load_cog(self, ctx: SlashContext, extension: str):
        await self.bot.load_extension(f"cogs.{extension}")
        await ctx.send(f"Loaded {extension} Cog")
#

now what is the problem in this code

#

AttributeError: 'CogCommandObject' object has no attribute 'sub_command'

lucid sun
silent portal
#

how can I detect this type of attachment?

#

in on_message event

weak tendon
# silent portal

I think these should be listed in message.attachments as well, check it

weak tendon
lucid sun
#

Sry I am not different accounts on windows and phone

weak tendon
#

Okay

weak tendon
#

There's no thing as SlashContext either

lucid sun
#

Huh

#

I import them from package discord_slash

weak tendon
lucid sun
#

Oh

weak tendon
#

So get rid of that

lucid sun
#

What to do now?

weak tendon
#

Rewrite the bot to dpy

#

The only solution

lucid sun
#

Bro my bot in dpy only

#

I am rewriting all commands to slash command

#

To i thought to discord_slash

weak tendon
lucid sun
#

I said it is dsy

weak tendon
#

If you have it imported it's that

lucid sun
#

Yea I just imported it

weak tendon
#

That library does not work

lucid sun
#

So what should I do

weak tendon
#

You already asked this question and I already answered

#

Not going into infinite loop

lucid sun
#

Bro I am saying how should I implement slash commands

#

Does Dsy support it?

weak tendon
lucid sun
#

How to do what to install?

weak tendon
#

I would link you a guide if I had it

#

But it's not in pins for some reason

dense swallow
#

is there an event for message publishes? if so what is it

slate swan
#

there is not

dense swallow
#

but then how does some bots send log msgs for that

slate swan
#

maybe i missunderstood what you mean message publish

#

do you mean when you click publish message on announcements channel?

dense swallow
#

yes

slate swan
#

well its not an event

dense swallow
#

hm

latent veldt
#
class Administration(commands.Cog):
    """This Cog is for the Administration of the Bot"""

    admin = app_commands.Group(name="admin", description="Admin commands")
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    

    @commands.is_owner()
    @admin.command(name="load", description="Load a cog")
    async def _load_cog(self, interaction: discord.Interaction, extension: str):
        await self.bot.load_extension(f"cogs.{extension}")
        await interaction.response.send_message(content=f"Loaded {extension} cog successfully.", ephemeral=True)
#

my command is not showing

slate swan
#

!d discord.Message.publish there is method to publish a message but i dont see how to receive an event when it does that

unkempt canyonBOT
#

await publish()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Publishes this message to the channel’s followers.

The message must have been sent in a news channel. You must have [`send_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.send_messages) to do this.

If the message is not your own then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) is also needed.
dense swallow
#

i see

#

so probably that was custom then?

slate swan
#

you may try asking the bot developers i guess

dense swallow
#

hm, ig btw i also have 1 more question

slate swan
#

then ask it

dense swallow
#

if i have on_message_delete, that only detects a single deleted msg right.does it detect bulk msg deletes or should i use on_bulk_message_delete

#

or on_raw_bulk_message_delete

slate swan
#

it explains the difference

#

oh wait wrong one

dense swallow
naive briar
#

Also check that you're syncing the commands

hushed juniper
#

How do you have spaces in slash command

glad cradle
#

iirc yes, lemme check

#

!d discord.Message.flags

unkempt canyonBOT
glad cradle
#

!d discord.MessageFlags.is_crossposted

unkempt canyonBOT
glad cradle
#

@dense swallow

slate swan
glad cradle
slate swan
#

then how does that make you get when it was published

glad cradle
glad cradle
#

which is different than when it was published

torn solar
#

how do i make a file a parameter for slash command

#

like this

fading marlin
#

Use discord.Attachment as the annotation for a parameter in your command

copper bronze
#
class Confirmer(View):
    def __init__(self, ctx, timeout):
        self.ctx = ctx
        self.button = Confirm_Button(id)
        self.callback = self.button.callback
        super().__init__(timeout=timeout)
        self.add_item(self.button)
        self.add_item(Cancel_Button(id))

i am not sure if above code is right or not, but i am trying to do is fit the code below into the view class.

I'm unable to do callback in code provided above.

view = ConfirmView(ctx=ctx, timeout=15)
                cancel = Cancel(id=f"{id}")
                confirm = Button(label="Confirm", emoji=tick, style=discord.ButtonStyle.green, custom_id=f"{id}d")
                view.add_item(confirm)
                view.add_item(cancel)
                confirm.callback = callback
modest harbor
#

Is there a way to set a disabled state for ui.Button?

robust fulcrum
vapid parcel
#

any good font to support like every single type of special character?

novel egret
#

i personally use "Luckiest Guy" but for the style your going for, I wouldn't use it in this case.

#

if you look up google fonts, adobe fonts, or like dafont.com, you can find some unique ones there and use them

vapid parcel
#

would they support special characters tho?

novel egret
#

i think so

weak tendon
#

Fancy fonts typically don't support everything and are just for latin, digits and basic symbols, sometimes cyrillic

#

With falloff font normal symbols will be rendered as expected, the "weird" ones will get rendered as falloff. Might look ugly but it's users fault for including those goofy ahh α€ͺ βΈ» ( Ν‘Β° ΝœΚ– Ν‘Β°) or whatever

vapid parcel
#

Oh so it will work if using falloff?

vapid parcel
#

What font does discord use?

weak tendon
vapid parcel
#

imma just

#

do username instead of display names.

#

display names is just causing to many issues atp GoofySkull

tight obsidian
#

the Noto family of fonts intends to support most of the unicode

modest harbor
#
    view.add_item(DownloadButton(label=f"Download media", url=url, style=discord.ButtonStyle.blurple, row=0, emoji="⬇️"))

doesn't seem to apply the color, any idea why?

fading granite
#

hi, i have a discord bot running on aws. it was able to handle 700-800 people easily. but now i want it to handle 10k+ people smoothly. i have never used aws paid tiers before. can someone guide me?

real mulch
modest harbor
real mulch
dense swallow
#

how do u get message from a channel? is there just one method, the channel.get_partial_message ?

#

theres also fetch_message, but i need to get the reactions from the msg, but get_partial_message.reactions doesnt exists

naive briar
#

It's for you to work with messages when you have their ID but don't want to fetch them

dense swallow
naive briar
#

Fetch the message

dense swallow
#

ok but it said it didnt have .reactions

naive briar
#

What said that?

dense swallow
#

oh wait, nvm

#

i forgot to await it, and it errored out

untold bear
#

So im working on a command to print the names of the members having a certain role in the server and when I make my bot iterate through the contents of ctx.guild.members, the only member it can find is the bot itself even when there are other people in the server

quick gust
#

is members intent toggled on in developer portal and your code?

#

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

untold bear
#

no, ill go and check it

untold bear
#
    async def members(self, ctx, *, role1: discord.Role):
        role = discord.utils.get(ctx.guild.roles, name=f"{role1.name}")
        l = []
        if role is None:
            await ctx.send(f'There is no "{role1}" role on this server!')
            return
        for member in ctx.guild.members:
            if role1 in member.roles:
                l.append(f"{member.mention}({member})")
                print(member)
                await ctx.send(f"{member.mention}({member})")
        if len(l) == 0:
            await ctx.send(f"Nobody has the role {role1}")
        else:
            res2 = "\n".join(l)
            print(res2)
            embed = discord.Embed(title=f"Members in {role1.name}", description=f"{res2}", colour=discord.Colour.blue())
            embed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar.url)
            await ctx.send(embed=embed)```
this is the command
golden portal
#

see what it prints

untold bear
golden portal
#

you didnt turn on members intents in code

untold bear
golden portal
#

yea no members intent

#

just do
intents.members = True

untold bear
#

oh ye so a separate 1 for members too?

#

thanks

#

its working perfectly fine now, tysm

golden portal
#

welcome

civic reef
#

I hosted my discord bot on EC2 instance. My bot going offline again and again. Like 5-6 times in a day. I don't know what to do. I just running the script again to make it online. But it's too tedious. What should I do?

ivory turret
#

Is there anyone who would like to build a discord bot with me?

civic reef
ivory turret
civic reef
untold bear
#
    async def on_message(self, message):
        banned_words = ["shit"]
        print(message.content)
        for word in banned_words:
            if word in message.content.lower():
                await message.delete()
                await message.channel.send("That is a banned word!")
        await self.bot.process_commands()```
I created this event to delete banned words but it seems like the bot cant see any messages. I have also enabled all intents via
intents = discord.Intents.all()
rugged shadow
#

in all seriousness though you should check the logs to fix the error instead of relying on these workarounds

untold bear
severe sonnet
#

guys

#

i forgot how to show picture using embed

#

what is the property of discord.Embed that allows me to show picture?

modest marsh
#

how do i make colorless embed

#

i tried doing the usual method and using the color that the background is but the little line still shows but when on other bots it doesnt

severe sonnet
#

okay guys what is the difference between thumbnail and image from discord.Embed ?

modest marsh
#

fixed

sick birch
severe sonnet
#

i see

mighty sun
#

hello all, can someone help me? i made a script so that when people write the words "classe, !, salon" it deletes the message for them and the bot responds for 5 minutes before deleting the message but it doesn't work... and i don't have any errors if possible please help me. thank you very much.https://pastebin.com/qtg9sHgB

civic reef
#

can anyone send some repos link of cool discord bots? (related to coding is good)

#

other is also fine

unkempt canyonBOT
untold bear
strong knoll
#

Anyone knows how to in discord.py disable select menus?

mighty sun
untold bear
mighty sun
untold bear
gilded ginkgo
#

hey gys

#

guys

#

can somebody help me i want to make a discord server small discord server

quick gust
untold bear
#

100% sure, checked the toggle and discord.Intents.all() in my code

quick gust
#

Just to make sure, ur bot isnt verified is it?

#

and is it in 100+ servers?

frosty roost
#

Is there a way to make a /say command and /edit command where the bot sends a message and if you use /edit (message ID) it will give you the existing message in your message bar and let you edit it

severe sonnet
#

like, to improve performance

#

i'm planning to make a releasing patch

#

i also need make it to make it have quality

#

for attract people to engage with my bot

untold bear
quick gust
#

hm

frosty roost
#

I have these lines setup to check your own event rewards and event points, it works fine when you use /balance (discord tag) but for normal /balance and /rewards it gives me the same errors message

#

Anyone know what I need to change?

slate swan
#

Interaction object does not have .author it has .user instead

frosty roost
#

So just change .author to .user? Sorry I'm pretty new to pythong and coding in general

slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
frosty roost
#

Thanks!

#

Alr well it just created another issue so Im not sure

glad cradle
#

d.py is not consistent

slate swan
slate swan
frosty roost
#

With a /buy command

#

I get this error

slate swan
#

so basically you can only once do interaction.response.send_message(...) if you try to do it two or more times on the same interaction you will get this error

#

if you want to send another message use interaction.followup.send(...)

frosty roost
#

Alright thank you alot, but now im getting this error, do follow up messages not need a delete after command to delete them?

frosty roost
slate swan
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

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

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
slate swan
#

look like you cannot put delete_after in followup.send

#

you have to delete it manually

frosty roost
#

Oh wow that really sucks

#

Is there no other way to code this? but with delete message

twilit linden
#

Problem?

still raft
#

!e import random def fair_coin_method(): return random.choice(['H','T']) ctr = 0 for x in range(100): curr = fair_coin_method() + fair_coin_method() if curr != 'HT': ctr+=1 print(ctr/100)

unkempt canyonBOT
#

@still raft :white_check_mark: Your 3.12 eval job has completed with return code 0.

0.74
still raft
#

OMG

still raft
#

@torn panther

twilit linden
#

Did you throw it for me

slate swan
twilit linden
magic stump
#

How can i ping in embed a channel?

slate swan
safe stag
#

How can I do this when I click a button because a Select should come up? How does that work? (in py-cord)?

swift siren
#

df is the activity type for custom

activity=discord.Activity(name=β€œrewrite because yes", type=4),

#

nvm I got it

primal wave
#

anyone knowss how to make ur bot run while ur pc is off

subtle jungle
#

even though i'm rarely using my discord bot, every time i call it, why do i get this error? i think the rate limit reset time might be calculating incorrectly, but im not 100% sure

shrewd apex
shrewd apex
weak tendon
primal wave
shrewd apex
#

^^

#

digital ocean is pretty decent imo

raw venture
#

Hey guys, how do you add a Cog class to a discord bot that inherits from commands.Bot? for example

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

    @commands.command(name='roll')
    async def roll(self, ctx: commands.Context):
        print("rolling...")
        random_number = str(random.randint(1, 6))
        await ctx.send(random_number)

using self.add_cog in the MyBot in the __init__ method of the class containing the implementations for the botdoesn't seem to be working

subtle jungle
weak tendon
thin raft
raw venture
#

Thanks!

thin raft
#

np

dry kelp
#

my main bot runs on docker, it has poetry so i have no issue with requirements

#

but i am making a secondary bot for self propose and its not letting me download a package

dry kelp
#

no no

#

this is another bot, trying to install disnake on my vps

weak tendon
#

I would recommend to use docker as well

#

Otherwise you need a venv

dry kelp
#

i just want to download disnake on it...

weak tendon
#

Global packages on linux are very messy to my experience

dry kelp
#

this is ubuntu

weak tendon
#

Linux distro

#

!venv

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
dry kelp
#

do you know how i could possibly install disnake? i would rather do that

weak tendon
#

Make a venv and install it there

dry kelp
#

what command do i use in a ubuntu vps?

#

nvm, got it thanks

#

@weak tendon

#

still need help

robust fulcrum
#

With what you need help?

weak tendon
#

And your pm is probably setup incorrectly

#

Do not use it, there's systemctl

#

Also there's always docker, I highly advise to use it instead

latent pier
#

Can i manually stop select menu after interaction just like buttons?

naive briar
#

Yes

frosty roost
#

Hey I was wondering how you can like show the discord user in an embed?

#

What is the command?

frosty roost
naive briar
unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
stray robin
#

Can someone tell me, what should I learn before making discord bots?

untold bear
#

what should i do to fix this?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
im trying to load data from a json file and as per my knowledge its a valid json.

glad cradle
stray robin
#

What IS python OOP

glad cradle
#

Object Oriented Programming in Python

stray robin
#

Ok, so can u tell examples, python hardest basics

glad cradle
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

untold bear
untold bear
naive briar
stray robin
#

Uu, sorry Im new here

#

Can I Ask..

Do you need
MongoDB token? To discord bot

naive briar
#

No

stray robin
#

Wait how you keep bot online then?

untold bear
naive briar
#

You need to run the bot with its token, not MongoDB token

stray robin
#

What IS The MongoDB for?

untold bear
naive briar
stray robin
#

Like store bot?

untold bear
shrewd fjord
quick gust
#

do any of you know of any program which logs the command usage, active users, and a bunch of other stats? and shows it on a web server with graphs and shit? I remember seeing something like that but I can't remember the name...

untold bear
#

its weird since ive made 2 projects before using json and ive never encountered something like this

shrewd fjord
stray robin
#

IS there in GitHub good discord bots? I noticed that I learn by reading codes, when I don't understand a Part, I Will learn what It means

untold bear
# shrewd fjord Try loading with `r+`

I dont get the same error anymore but now im getting a key error and for some reason its creating a new entry when i try to enter data using the same key

shrewd fjord
untold bear
untold bear
shrewd fjord
#

And for json.dump r+ should work too, if doesn't then try w+

untold bear
#

why is it creating a new entry with the same key in the dictionary

untold bear
#

and load as well

sterile sandal
sterile sandal
untold bear
#

ig ill just remake the code, i cant find the error 😭

shrewd fjord
untold bear
shrewd fjord
#

Something wrong with the if-else statement then

untold bear
#

So why is it going wrong 😭

shrewd fjord
#

!e

d = {"1": 1, "1": 3}
print(d)
#

Wow it just merges it i think

unkempt canyonBOT
#

@shrewd fjord :white_check_mark: Your 3.12 eval job has completed with return code 0.

{'1': 3}
untold bear
#

Wha

shrewd fjord
#

Well yeah it just switches to latest assigned one, not sure if same for json tho

untold bear
#

It's not even merging in my case

#

Yeah guess I'm remaking it

shrewd fjord
#

It aint merging, its just using the 2nd latest one something like variable

a=1
a=2
>>>a
2
glad cradle
glad cradle
#

and the json file itself is not supposed to have duplicated keys

shrewd fjord
untold bear
#

some witchcraft is going on

glad cradle
#

i mean

#

use a db?

untold bear
#

Idk how to use any db except mysql

shrewd fjord
#

!pip aiosqlite

unkempt canyonBOT
shrewd fjord
#

!pip asqlite

unkempt canyonBOT
glad cradle
#

the former is better

shrewd fjord
#

Both uses a db like file
(file.db, file.sqlite, file.sqlite3)

untold bear
#

Okay

frosty roost
#

I keep getting this error when trying to embed

slate swan
#

!indent

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

frosty roost
#

Thank you :D

frosty roost
#

The command works as intended but it always does that sending command for 5 seconds

#

And then turns into this

frosty roost
#

And i dont even get an error message in the console, what am i doing wrong here?

naive briar
#

You need to respond to the interaction

#

Not just send a message to a channel

untold bear
frosty roost
#

Thanks

ancient raven
#

Hello there , I'm considering to get a hetzner dedicated server to host my bot. It's not a heavy bot though but I need 100% uptime. Any suggestions?

maiden pilot
#
        if message.channel.id == target_channel_id:
            lfg = "lfg"
            bot_message = await message.channel.send(lfg)

            if message.id != bot_message.id:
                await bot_message.delete()
                print("LFG guide reposted")```

I'm trying to check if the last message was posted by the bot or not, but it wont work, can someone help?
wheat gazelle
#
@client.event
async def on_message(message):
    if message.author.bot:
        print("it\'s a bot !")
    else:
        print("it\'s not a bot !")```
#

try to use this logic

grizzled sequoia
#

Hey,
I am looking for a solution that will allow me to send a message "notification" on discord at a given date: for example, in 3 months at a given time. How to approach this, what to use? Celery, RQ or something else?

vapid parcel
naive briar
#

(don't resize them too much)

vapid parcel
naive briar
vapid parcel
#

Yes, but how

#

how can i not resize them so much?

naive briar
#

Don't resize them to the point that they become pixelated 🫠

naive briar
vapid parcel
#

what would be a recommend size?

weak tendon
stray robin
#

Can Someone give me BASIC discord bot 'background.

Im meaning ready-coded thing, like It has already responses.py and that stuffs.

( I only read by reading codes, so when ill have them, ill 'translate' them and understand The lines by Step by Step. )

Can send in dms, / GitHub, send link If GitHub.

(Note: skemers, I won't download pip install trash, All I can pip install IS pip install discord or It was pip install discord.py anyways, If someone can Help and give on dms.

Ik there's few on GitHub, but idk If virus, and etc.. I won't understand them

#

**I Will fill The

TOKEN =

or

DISCORD_TOKEN =**

stray robin
#

If It makes Image to size, you should use The recommend size as size + extra. ( when bigger gets smaller, quality gets little better )

golden portal
stray robin
#

Okay

#

So I download this as zip?

#

( My goal IS to Make own DC bot, but at first I need to learn Make commands like )

!Ban userid / @user

golden portal
#

you dont really have to download it, each example is just 1 file, you can just read the code and try it out

#

each file covers a concept that the library offers

weak tendon
stray robin
#

Okay..

stray robin
#

Like checks files?

golden portal
#

from the looks of it, it's disnake so it's not dpy

stray robin
stray robin
#

The github

golden portal
weak tendon
weak tendon
ancient raven
#

And don't wanna get rate limited sharing same IP with 100 others

weak tendon
#

And I doubt you need a dedicated server, virtual will do

#

Dedicated is a whole personal machine, they are typically more powerful (hence more expensive) and are meant for higher load than a basic discord bot. As long as its CPU and memory usage does not exceed limits

ancient raven
#

So vultr vps or hetzners works ig ?

weak tendon
weak tendon
ancient raven
#

Oh ic, thanks

naive briar
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

safe stag
#
Hey guys! I'm currently facing a small issue with my bot. It claims that it can't find the categories even though the category ID is already stored in the database. Could someone please help me out? I'd really appreciate it!```  ```py
class CreateTicketSelect(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.select(
        custom_id="ticket_select",
        min_values=1,
        max_values=1,
        placeholder="Select a category for your ticket",
        options=options,
    )
    async def ticket_select_callback(self, select, interaction):
        category_name = select.values[0]
        category = discord.utils.get(interaction.guild.categories, name=category_name)
        
        if category:
            guild_id = interaction.guild.id
            category_id = category.id
            channel_id = None 
            await db.create_ticket(guild_id, category_id, channel_id)

            overwrites = {
                interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
                interaction.user: discord.PermissionOverwrite(view_channel=True, read_message_history=True, send_messages=True),
                interaction.guild.me: discord.PermissionOverwrite(view_channel=True, read_message_history=True, send_messages=True),
            }

            channel = await category.create_text_channel(name=f"{interaction.user.display_name}", overwrites=overwrites, topic=interaction.user.name)
            embed = discord.Embed(
                title="Ticket Created",
                description="Support will be with you shortly.",
                color=discord.Color.green()
            )
            await channel.send(embed=embed, view=CloseTicket())
            await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}", ephemeral=True)
        else:
            await interaction.response.send_message("I 🚫 find the specified category.", ephemeral=True)```
shrewd fjord
unkempt canyonBOT
#

class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.

Please note that if you use this in a private message with a user, no channels will be displayed to the user.

New in version 2.1.
frosty roost
#

So this is my code for getting multiple options when using /fruit but I would like the display names of the fruits to have capital letters and space for example apple displaying as Apple Pie how can I do this?

#

Is there a way for that? cuz I've seen other bots with spaces and capital letters in their options

unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 89

# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):
    """Interact with the shop"""
    await interaction.response.send_message(f'Action: {action}\nItem: {item}')```
shrewd fjord
#

Literal is easy imo

#

Yo catty sup

frosty roost
#

Yeah tried those when following some videos but never worked for me always got some errors but ill try again maybe im just missing commas

naive briar
#

Hii 🐈

frosty roost
#

ty