#discord-bots

1 messages · Page 348 of 1

sharp dome
#

hm?

#

UH

balmy bison
viscid hornet
# sharp dome hm?

you've told discord to call your Interaction stuff "button" and all your Button stuff "interaction"

viscid hornet
sharp dome
#

like how :3

viscid hornet
#

look at my example again

sharp dome
#

fixed

#

now an other problem, how to check if the user that clicked the button is the one who made the embed?

#

and how to remove the button after clicking ti?

viscid hornet
sharp dome
#

alr

viscid hornet
sharp dome
viscid hornet
#

did you even specify a thing to be removed?

#

or did you copy and paste again?

sharp dome
#

self.remove_item(button)

sharp dome
viscid hornet
#

yep

sharp dome
#

in the:

@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green) async def confirm(self, interaction, button):
Correct?

#

well it's doesn't work

viscid hornet
viscid hornet
sharp dome
#

nop

#

it's should remove it correct?

sharp dome
#

see the button it's still there something is wrong

viscid hornet
#

you need to edit the message after if you want it to show up

viscid hornet
sharp dome
#

wdym

#

because this how it should workl

#

I need to remove that button ong

#

but anyway how to do?

viscid hornet
# sharp dome wdym

you need to edit the message with the view for the changes to show up ```py
class ExampleView(ui.View):
...
async def on_timeout(self):
for item in self.children:
item.disabled = True

    await self.message.edit(view = self)```
#

this is an example using on_timeout which happens when the view expires

viscid hornet
sharp dome
#

what is message?

viscid hornet
sharp dome
#

ok

#

hm

#

something is wrong, it ain't working now

#

the interaction

viscid hornet
sharp dome
#

the button now get removed...

#

bruh

viscid hornet
sharp dome
#

no

#

i want to get removed after i clicked it

viscid hornet
#

“i want them to be removed” “why are they removed”

sharp dome
#

:3

viscid hornet
sharp dome
#
class Confirm(discord.ui.View):
    message = None

    def __init__(self, user_id, user_data: user_data_manager, amount_to_float: float):
        super().__init__(timeout=None)
        self.user_id = user_id
        self.user_data = user_data
        self.amount_to_float = amount_to_float

    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
    async def confirm(self, interaction, button):
        if interaction.user.id == self.user_id:
            user = self.user_data.get_user(interaction.user.id)
            create_embed_coinflip = discord.Embed(
                title=":white_check_mark: Coinflip Created",
                description=(
                    ":gems: **Gems**: {}\n"
                    ":gems: **New Balance**: {}\n"
                    ":crown~1: **Channel**: <#{}>"
                ).format(
                    number_converter.number_to_suffix(self.amount_to_float),
                    number_converter.number_to_suffix(user.balance - self.amount_to_float),
                    cfg.FLIP_COIN_CHANNEL_ID),
                color=discord.Color.purple())
            create_embed_coinflip.set_footer(text=f"{cfg.BOT_NAME} - Coinflip Created")
            self.user_data.remove_balance(interaction.user.id, self.amount_to_float)
            self.user_data.add_wagered(interaction.user.id, self.amount_to_float)

            await interaction.response.send_message(embed=create_embed_coinflip)

            self.remove_item(button)
            await self.message.edit(embed=create_embed_coinflip, view=self)
        else:
            await interaction.response.send_message("You can't confirm this.", ephemeral=True)
#

uh????

#

help me

vapid parcel
#

Anyone?

viscid hornet
#

and also use guard classes to prevent bulging code

sharp dome
#

still nothing

#
[2024-03-29 18:30:07] [ERROR   ] discord.ui.view: Ignoring exception in view <Confirm timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Confirm' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 98, in confirm
    await interaction.response.send_message(embed=create_embed_coinflip)
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\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```
viscid hornet
#
# don't do this
if ...:
    if ...:
        if ...:
            ...
        else:
            ...
    else:
        ...
else:
    ...

# do this
if not ...:
    return

if not ...:
    return

if not ...:
    return```
sharp dome
#
    await interaction.response.edit_message(view=None)
    await interaction.response.send_message(embed=create_embed_coinflip)
viscid hornet
sharp dome
#

oke

sharp dome
viscid hornet
#

.response. is a response

#

it says there

#

you have responded to the interaction

#

you cannot respond twice so it'll raise an error if you try that

sharp dome
#

yea I see it

#

i need to send 2 message

#

how to do?

#
await interaction.response.edit_message(view=None)
            await interaction.followup.send(embed=create_embed_coinflip)
#

like this?, it workin!

#

at least it correct?

viscid hornet
#

editing makes more sense imo but you do you 🤷🏽‍♂️

viscid hornet
#

@sharp dome do you need any more help? i was going to do an important phone call but i put it off to help you

viscid hornet
viscid hornet
autumn pewter
#
import discord
from discord.ext import commands
import datetime

welcome_channel = 1221421626202001470

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot("~", intents=intents)

@client.event
async def on_connect():
    print("connected")

@client.event
async def on_member_join(member):
    channel = client.get_channel(welcome_channel)
    embed = discord.Embed(
        description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
        color=0x000000,
        timestamp=datetime.datetime.now(),
    )
    channel.send(embed=embed)

client.run("")

can anyone explain 2 me y this aint working

#

its still not sending the message uppon joining

viscid hornet
#

any errors?

#

extra details would be helpful

autumn pewter
#

no error

#

just doesnt do what i should

slate swan
#

The error is that you're not awaiting .send()

#

You're not getting an error because the members intent is also not enabled, so the event won't get triggered at all and your code won't be executed either

autumn pewter
#

where do i need to add where : (

slate swan
#

Enable the members intent
Add await on your .send() line

autumn pewter
#

okay lemme try now

sharp dome
#

help

autumn pewter
sharp dome
#

help

[2024-03-29 19:46:50] [ERROR   ] discord.ui.view: Ignoring exception in view <CoinFlipButtons timeout=None children=3> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='Cancel' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 251, in cancel
    await interaction.edit_original_response(view=None)
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\interactions.py", line 487, in edit_original_response
    data = await adapter.edit_original_interaction_response(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```


 ```py
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
    async def cancel(self, interaction, button):
        coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
        if coin_flip is None:
            await interaction.response.send_message("Coinflip not found.", ephemeral=True)
            return

        if coin_flip.started:
            await interaction.response.send_message("Coinflip already started.", ephemeral=True)
            return

        if interaction.user.id == coin_flip.user_id:
            coin_flip.cancelled = True
            await interaction.edit_original_response(embed=coinflip_embed_battle(self.user_name, coin_flip), view=None)
            self.coin_flip.remove_coin_flip(coin_flip.coin_flip_id)
            user_data_manager.get_user(interaction.user.id).balance += coin_flip.amount
            user_data_manager.add_wagered(interaction.user.id, -coin_flip.amount)
            await interaction.followup.send("Coinflip cancelled.", ephemeral=True)
#

please

#

@viscid hornet help buddy

viscid hornet
sharp dome
#

idk

#

I'm dumb

#

interaction.response.edit_message

this is thje correct

viscid hornet
#

thats for when you HAVEN'T responded to the interaction before

#

a response is anything with .response.

#

so you cant do something like this py await interaction.response.defer() await interaction.response.send_message("hello")

sharp dome
# viscid hornet so you cant do something like this ```py await interaction.response.defer() awai...
  interaction.response.defer()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
[2024-03-29 20:07:12] [ERROR   ] discord.ui.view: Ignoring exception in view <CoinFlipButtons timeout=None children=3> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Call bot' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 288, in call_bot
    await self.flip_coin(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 227, in flip_coin
    await self.run(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\coinflip_game_mode.py", line 237, in run
    await interaction.response.edit_message(embed=coinflip_embed_battle(self.user_name, coin_flip),
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\interactions.py", line 888, in edit_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```

```py
@discord.ui.button(label="Call bot", style=discord.ButtonStyle.blurple)
    async def call_bot(self, interaction, button):

        coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
        if not await validate_coin_flip(interaction, coin_flip):
            return

        if interaction.user.id == coin_flip.user_id:
            coinflip_offender = self.bot.user.id
            if coin_flip.heads_player == "Undecided":
                coin_flip.heads_player = "<@{}>".format(coinflip_offender)
            elif coin_flip.tails_player == "Undecided":
                coin_flip.tails_player = "<@{}>".format(coinflip_offender)

            interaction.response.defer()
            await interaction.response.send_message("Bot joined the coinflip.", ephemeral=True)

            if coin_flip.heads_player != "Undecided" and coin_flip.tails_player != "Undecided":
                await self.flip_coin(interaction)
viscid hornet
#

because the interaction has already been responded to

sharp dome
#

the flip_coin modify the messages

viscid hornet
#

(all .response. things need to be awaited btw)

sharp dome
#
    async def flip_coin(self, interaction):
        coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)
        while not coin_flip.ended:
            await self.run(interaction)
            await asyncio.sleep(1)

    async def run(self, interaction):
        coin_flip = self.coin_flip.get_coin_flip(self.coin_flip_id)

        if coin_flip.seconds > 1:
            if not coin_flip.message_has_sent:
                coin_flip.started = True
                coin_flip.time = f"<t:{int(time.time() + coin_flip.seconds)}:R>"
                await interaction.response.edit_message(embed=coinflip_embed_battle(self.user_name, coin_flip),
                                                        view=None)
                coin_flip.message_has_sent = True
            coin_flip.seconds -= 1
        else:
            coin_flip.flip_coin()
            coin_flip.started = False
            await interaction.edit_original_response(embed=coinflip_embed_battle(self.user_name, coin_flip), view=None)
            coin_flip.ended = True
            define_winner(coin_flip)
            self.coin_flip.remove_coin_flip(coin_flip.coin_flip_id)
balmy bison
viscid hornet
balmy bison
#

@viscid hornet checkkk

long oxide
#

Hi

#

How are you

#

Boys i want to create discord bot use python

#

Where should I start?

#

I will use replit

viscid hornet
viscid hornet
#

dont use replit, it'll choke your bot performance and its far easier to just write the code yourself in an IDE like vscode

viscid hornet
long oxide
#

İ dont have pc

#

😭

viscid hornet
#

idk how you program without a pc but oh well

#

you kinda do need a pc for this sort of stuff

long oxide
#

İ cry my toilet

glad cradle
#

tf

stuck cliff
snow coral
#

how can i make a button not time out

#

would i just set timeout to none

sharp dome
#

hello

#

how Can i run quart and discord bot thogheter?

#
import discord
from discord.ext import commands

from config import config as cfg
from game_modes import game_modes_commands
from user import deposit_data_manager
from user import user_commands, user_data_manager as user_data_manager

bot = commands.Bot(command_prefix="$", intents=discord.Intents.default())
deposit_data_manager = deposit_data_manager.DepositManager()


@bot.event
async def on_ready():
    user_data_manager.load_users()
    print(f"Logged in as {bot.user}")
    try:
        await bot.add_cog(user_commands.UserCommands(bot, user_data_manager, deposit_data_manager))
        await bot.add_cog(game_modes_commands.GameModesCommands(bot, user_data_manager))
    except Exception as e:
        print(f"Failed to add Balance cog: {e}")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {synced} commands")
    except Exception as e:
        print(f"Failed to sync commands: {e}")


def run():
    bot.run(cfg.TOKEN)
#

then i have this clas:

import discord
from quart import Quart, request

from config import config as cfg
from user import user_data_manager
from user.deposit_data_manager import DepositManager

quart = Quart(__name__)


async def start_quart():
    await quart.run_task(debug=False, port=80, host="0.0.0.0")


class RobloxBot:
    def __init__(self, bot, deposit_data_manager: DepositManager, user_data: user_data_manager):
        self.bot = bot
        self.deposit_data_manager = deposit_data_manager
        self.user_data = user_data

    @quart.route('/deposit_request', methods=['POST'])
    async def deposit_request(self):
        data = await request.get_json()
        user_id = data['user_id']
        code = data['code']
        successful_deposit = data['successful_deposit']

        deposit = self.deposit_data_manager.get_deposit(user_id)
        if deposit is not None:
            if deposit.code == code and deposit.successful_deposit:
                deposit.successful_deposit = successful_deposit
                deposit.balance = data['balance']
                deposit.successful_deposit = data['successful_deposit']
                user = self.user_data.get_user(user_id)
                if user is not None:
                    user.balance += deposit.balance
                    user.deposited += deposit.balance
                    self.user_data.save_users()
            self.deposit_data_manager.save_deposits()

        return "OK"

    async def run_embeds(self):
        deposits = self.deposit_data_manager.get_deposits()
        while deposits is not None:
            for user_id, deposit in deposits.items():
                if deposit.successful_deposit:
                    user = self.user_data.get_user(user_id)
                    if user is not None:
                        embed = discord.Embed(
                            title="Deposit successful",
                            description=f"Your deposit of {deposit.balance} has been added to your balance",
                            color=discord.Color.green()
                        )
                        channel = self.bot.get_channel(cfg.DEPOSIT_CHANNEL_ID)
                        await channel.send(embed=embed)
#

idk how to and even AI doesn't know how to use python

vapid parcel
#

Yo can someone help me? So when I add my bot into a server, it shows the commands of the bot in the server, but the bot isn't in the server?

balmy bison
balmy bison
#

@sharp dome dmss

sharp dome
vapid parcel
#

Does dpy have support on user install yet?

viscid hornet
#

like yk when you leave your screen on and showing something for too long

vapid parcel
#

Nah I fixed it

viscid hornet
#

it leaves a little marking that stains the screen

#

its kinda like that

vapid parcel
#

its cuz the permissions was none

#

discord reset it for some reason

viscid hornet
#

thats strange

viscid ridge
#

is there a good example on slash commands?

viscid ridge
midnight oracle
#

How do streaming music bots work now days after the Discord Policy change?

viscid ridge
vapid parcel
#

Does anyone know how to put a command behind the pay wall in dpy?

naive briar
#

Use checks

vapid parcel
#

any docs on this?

#

cuz im trying to use the SKU

zenith yarrow
#
  @app_commands.command()
  async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_link: str):

    ids = extract_ids(message_link)
    print(ids)
    channel_id = ids[1]
    print(channel_id)
    message_id = ids[2]
    print(message_id)
  
    channel = self.bot.get_channel(channel_id)
    message = channel.get_message(int(message_id))
    await message.add_reaction(emoji)
    
    c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
    conn.commit()
    await interaction.response.send_message("done",ephemeral=True)
    ```
How do u add reaction to a message?
zenith yarrow
zenith yarrow
golden portal
#

channel there is a None type meaning your bot can't find the channel

#

can you do print(type(channel_id)) see what it prints

zenith yarrow
golden portal
#

get_message doesnt exist

#

!d discord.TextChannel.get_partial_message

unkempt canyonBOT
#

get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialMessage) from the message ID.

This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.

New in version 1.6.

Changed in version 2.0: `message_id` parameter is now positional-only.
golden portal
#

use that instead since all you need is adding a reaction

vapid parcel
#

Anyone have docs on how the SKU works with a dpy bot?

vapid parcel
shrewd apex
#

oh

golden portal
golden portal
# vapid parcel Anyone have docs on how the SKU works with a dpy bot?

seems like no one did the docs yet because it's new, once you create an SKU the flow of it looks like,
user subscription -> entitlements -> on_entitlement_create, so i would imagine you just have to store that entitlement and check with a command check to see if the user have entitlement, after that you can prompt them with InteractionResponse.require_premium if they dont have it

there are also Bot.create_entitlement to test entitlement triggers based on this doc

spice warren
#

The SKU stuff is still a work in progress, and following the discord docs on it isn't very enlightening either, but I think flowerpad nailed it yeah

golden portal
viscid hornet
drifting arrow
#

Will the new polls feature be part of the discordpy?

slate swan
#

yes

drifting arrow
#

Is it already and Im just being silly for not looking?

slate swan
#

i know its already implemented in disnake dunno about discord.py but for sure will be

#

DisnakeDev/disnake#1176

lament depotBOT
slate swan
#

Rapptz/discord.py#9759

lament depotBOT
slate swan
#

just need to wait for pr accept and release

leaden olive
#

why none

pale zenith
leaden olive
#

self.pool = await aiomysql.create_pool(host='', port=, user='', password='', db='', loop=loop, autocommit=True, maxsize=25)

lethal inlet
#

can anyone help me to create a discord bot

#

sry but i cant pay anything as i am poor

#

if you can help pls dm me

sharp dome
#
channel = self.bot.get_channel(int(cfg.DEPOSIT_CHANNEL_ID))
            await channel.send(
                f"<@{user.user_id}> has successfully deposited {number_converter.number_to_suffix(deposit.balance)}",
                embed=embed)
#
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1376, in handle_request
    return await self.full_dispatch_request(request_context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1414, in full_dispatch_request
    result = await self.handle_user_exception(error)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1007, in handle_user_exception
    raise error
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1412, in full_dispatch_request
    result = await self.dispatch_request(request_context)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\quart\app.py", line 1506, in dispatch_request
    return await self.ensure_async(handler)(**request_.view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\utils\roblox_bot.py", line 50, in deposit_request
    await channel.send(
          ^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'send'```
#

why???

#

help

naive briar
#

channel is None 🤷

sharp dome
#

no way

#

i know, but the channel exists ;-;

naive briar
#

Do you have that code run before the bot is ready? The channel cache will not be ready until then

sharp dome
#

yes

balmy bison
#

@naive briar

naive briar
sharp dome
# naive briar Why?
class Bot:
def __init__(self, bot: commands.Bot, deposit: DepositManager, user: user_data_manager):
        self.bot = bot
        self.deposit = deposit
        self.user = user
bot = commands.Bot(command_prefix="$", intents=discord.Intents.default())
myclass = Bot(bot)
#

this is correct?

young dagger
#

How can I delete messages that contain headers?

#

Example

Header

quick gust
#

i dont think theres any option other than regex

young dagger
#

Or is there any better way to do it?

quick gust
#

seems fine

#

but im not a regex expert

naive briar
#

Try .search instead

#

!e

import re

print(re.match("^#.*?", "A\n# Something", re.MULTILINE))
print(re.search("^#.*?", "A\n# Something", re.MULTILINE))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | None
002 | <re.Match object; span=(2, 3), match='#'>
quick gust
#

oh yeah match only checks if its at the beginning right?

naive briar
#

Yes

icy bison
#

i have a text file which contains around 500 lines of different links and i want to send those links at a 5 min interval to one of my discord channel

#

can anyone help me make a discord bot ?

young dagger
naive briar
#

Show your code

young dagger
# naive briar Show your code

Nvm. It worked now

        header_pattern = re.compile(r'^#+\s+.*$', re.MULTILINE)

        if header_pattern.search(message.content):
            await message.delete()```
#

I can still use re.compile

naive briar
#

Yes

young dagger
#

Thanks Cat

midnight oracle
#

any idea why I receive this error when trying to install discord-component?

Collecting discord-component
  Using cached discord_component-2.1.2.tar.gz (12 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error
  
  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [19 lines of output]
 
          file = builtins.open(filename, mode, buffering)
      FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.
blissful crane
hushed galleon
#

huh, it looks like an unofficial reupload of the original discord-component__s__ library that the author yanked

tender bobcat
#

Dark magic related to discord onboarding (Server Guide) -> Resource

You can fit everything any text channel with @ everyone to view the channel. This make a good opportunity to hide auto role embed in there from bot. Even better, the author of the embed can be stay hidden on client-side which might be helpful in some case. Furthermore, you can add thumbnail, title and description to further descript to the user what they should do. (Example: Verification)

In addition, the resource button is being hidden if the user can no longer access the channel, which could make the whole process incredibly interactive (e.g. disappear after obtaining the role)

#

Extensionally, it doesn't have to restricted to channel that always visible to people just join. This can be accomplished by auto role a role that hide the channel on join/Using onboarding pre-join question to forcibly assign the role so people with bare @ everyone do not exist

#

Which therefore you can set freely on what resource to display to what user in the server (even tho It might mean the whole permission system have to be reworked)

frigid estuary
#

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

frigid estuary
#

ignore that ij forgot the website

slate swan
#

hi

#

Does anyone know why the discord API doesn't want to interact with my user token?

#

401: Unauthorized

blissful crane
slate swan
blissful crane
#

self bots (passing a user token) are not allowed and break discord tos

slate swan
#

well, previously if he left me, out of nowhere now that comes out to me

#

and I have tools (selfbots) that do work well with my token, but not with my code, I don't know why

slate swan
#

?

blissful crane
#

nvm, anyway. As selfbots are against tos, you won't be getting help for them here

slate swan
#

hahahaha

#

ok, thank you

proud swallow
#

hello i am new here. I wanna start to program a discord bot, any advice for me?

golden portal
small venture
#

can someone help me with this

naive briar
#

Did you save the file?

small venture
#

Yeah

naive briar
small venture
#

I saved it again and it says this now

naive briar
#

You need to import commands from discord.ext instead, that's where it's from :P

small venture
#

OOOH

#

I don't know why I keep getting this error because I gave the token

naive briar
#

Did you put the token into the run method like: bot.run("token")?

#

Doesn't seem like it, based on the traceback

small venture
#

I did bot.run("token")

#

but the token is my bot token so Idk whats wrong with it

naive briar
#

Did you save the file?

small venture
#

yeah

naive briar
#

Then the error should go away ducky_concerned

small venture
#

it doesn't :/

#

I fixed it

#

thanks for the help:D

naive briar
#

Nice 🐈

light violet
#

i need help

#
/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py:464: RuntimeWarning: coroutine 'setup' was never awaited
  setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/client.py", line 703, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/BattleEx/main.py", line 13, in on_ready
    await bot.load_extensions("cogz")
TypeError: object NoneType can't be used in 'await' expression```
#
import aioredis,asyncio
from disnake.ext import commands
import os

from disnake.ext import commands 
import os


class Redis(commands.Cog):
    """For Redis."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.pool = None
        self._reconnect_task = self.bot.loop.create_task(self.connect())

    #all funcs here

async def setup(bot: commands.Bot):
  print("Here")
  redis_cog = Redis(bot)
  print("Setting up Redis cog...")
  await redis_cog.connect()

  await bot.add_cog(redis_cog)```
naive briar
light violet
naive briar
#

What is the version? The asynchronous implementation is added in 2.0+

light violet
#

;

light violet
#

how do use async funcs in cogs

#

for disnake then

naive briar
#

You cannot

light violet
#

then how do i use components in ctx.send in dpy @naive briar

naive briar
#

Use its discord.ui module

#

!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.
light violet
naive briar
#

There's no such thing in discord.py

#

!d discord.ext.commands.Context.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.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.

For interaction based contexts this does one of the following...
light violet
# naive briar There's no such thing in `discord.py`

Here
Setting up Redis cog...
Extension 'cogz.redis' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
/home/runner/BattleEx/main.py:23: RuntimeWarning: coroutine 'Redis.connect' was never awaited
print(e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded

#

print("Here")
redis_cog = Redis(bot)
print("Setting up Redis cog...")
gg=asyncio.run(redis_cog.connect())

#

what else can i do

viscid hornet
pale zenith
#

Why is asyncio.run being used here...?

small venture
#

async def ticketcallback(interaction):
guild = interaction.guild
role = discord.utils.get(guild.roles, name="Ticket Support")
overwrite = {
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="Other Ticket", value="02", emoji="❌", description="This will open a in the other section")
])

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=overwrite)
        await interaction.response.send_message(f"Created ticket - <#{channel.id}", ephemeral=True)
        await channel.send("Hello, how can can I help?")
    elif select.values[0] =="02":
        category = discord.utils.get(guild.categories, name="Tickets2")
        channel = await guild.create_text_channel(f"{interaction.user.name}-ticket", category=category, overwrites=overwrite)
        await interaction.response.send_message(f"Created ticket - <#{channel.id}", ephemeral=True)
        await channel.send("Hello, how can can I help?")

        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="📥 Create 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)

#

Can someone help mewhy this isn't working

#

I get a button which says "📥 create ticket" but when I click it says "This interactions failed"

#

it also does not give errors

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

viscid hornet
#

its something to do with the callback not being defined properly

#

since it requires arguments and you cant do what you’re doing if there are arguments there

#

you should define complex stuff like buttons in a physical class instead of a few lines

#

makes it easier to debug as well

mossy jacinth
#

what is this called or how can i do something like this?

golden portal
unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
golden portal
#

you can also use typing.Literal or autocomplete, depending on what you want

toxic breach
#

I am having AttributeError: type object 'datetime.datetime' has no attribute 'datetime' error

#
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#

can anyone help?

vivid holly
toxic breach
#

ohhhhh yessss

#

thx broo

light violet
#

why dont i get the button click event response


class BattleUI(discord.ui.View):
  def __init__(self,bot):
      super().__init__()
      self.selected_button = None
      self.bot=bot

  async def start(self, ctx,pokemon):
      
      for n,i in enumerate(pokemon.moves):
        button = Button(style=discord.ButtonStyle.secondary, label=f"{i.move_name}", custom_id=f"{n}")
        self.add_item(button)  
      def check_button(i: discord.Interaction, button):
        return i.author == ctx.author and i.message == msg
      message = await ctx.send("Please choose a move:", view=self)
      interaction, button = await self.bot.wait_for('button_click')
      print("Button clicked")
      action=button.custom_id
      print(interaction.data)
      print(self.items)
      await interaction.message.edit_response(view=self)```
slate swan
#

Because button_click is not an event

#

Here's an example of how buttons actually work

digital crypt
#

so im trying to make a bot, kinda need opinion what you would have inside a guild setting , this is example of what i have stored

"alliance_settings":{
            "alliance_description": "We are a powerful alliance!",
            "alliance_roles":{"warlord":0,"diplomat":0,"resercher":0}
        }
glad cradle
#

are you using json as a database?

digital crypt
#

i plan to move to mysql

digital crypt
#

so @glad cradle gib answer

#

ig json killed him

glad cradle
#

the structure how you store things is up to you

#

it just needs to be functional for you

#

there isn't a correct way

digital crypt
#

wel it is functional

glad cradle
#

but surely don't use json pls

digital crypt
#

also whats the harm in that?

glad cradle
#

how are you reading and opening the json file? file operations are blocking

glad cradle
digital crypt
digital crypt
#

ill keep that in mind in future

#

rn, this is just a personal discord bot

digital crypt
#

what more can i add?

finite salmon
#

youre supposed to use json.load() right

digital crypt
finite salmon
#

and json.dump

digital crypt
#

yea

finite salmon
digital crypt
#

iforgot lol

#

been long time since i made a bot

#

anyways thats not an excuse for me

#

i shall fix my mistakes immediately

finite salmon
#

Just store the data which you think your bot needs to use

#

And if you're using mysql or sqlite etc use an async library of it

digital crypt
#

so need nommethings that i can put in there

finite salmon
#

Well that completely depends on you, I haven't seen your codebase so see what all data you exactly need to store

digital crypt
#

its just additional info

#

imma get full structure

#
"server_id":{
        "leader":0,
        "alliance_name":"no name",
        "alliance_battles":0,
        "alliance_battles_won":0,
        "alliance_battles_lost":0,
        "alliance_power":0,
        "alliance_members":[],
        "alliance_allies":[],
        "alliance_settings":{
            "alliance_description": "We are a powerful alliance!",
            "alliance_roles":{"warlord":0,"diplomat":0,"resercher":0},
            "alliance_ranks":{"rank4":[],"rank3":[],"rank2":[],"rank1":[]}
        }
    }
naive briar
#

That looks cool

digital crypt
#

as a solo dev ive been trying my best for past 2 years along with acedimic studies(im not even in collage right now, im undergradguate) The actual time i spent on this bot may be around 15-30 days

weak tendon
naive briar
#

Haven't seen them for a while

slate swan
digital crypt
#

im kinda confused

digital crypt
#

heres proof

#

also @weak tendon wdym by real sarth?

digital crypt
#

anyone?

slate swan
glad cradle
digital crypt
#

oh wait that ,, no

glad cradle
#

mh then it should be fine even tho not reccomandable

#

writing on the file is another thing tho, always blocking

digital crypt
glad cradle
digital crypt
#

cause when im calling thee fuction, data needs to be updated contounisouly

glad cradle
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
digital crypt
glad cradle
#

why don't you use a database from now on

#

You shouldn't delay it anymore longer

digital crypt
#

and im not currently comdortable

#

thats why ive been avoiding it

glad cradle
digital crypt
#

i see

#

ig something happened to him?

#

well there are 9 of us in this server

glad cradle
# digital crypt welp i got my exams

mh, ic, switching to a database shouldn't be too hard and shouldn't require much code changes, i would suggest to not focus on the data storage on json files, instead focus on the functionalities, so you will not waste time on a thing that you'll surely switch later

glad cradle
#

probably the latter

digital crypt
#

he prob studying

#

ig he took cs?

glad cradle
#

idk, iirc yes

weak tendon
digital crypt
#

kk

viscid hornet
#

i wrote two gists on this sort of stuff but idk if i can send the link

viscid hornet
#

might be classed as self promotion

digital crypt
#

just not used to using it

abstract granite
#

How use from src.settings import config

viscid hornet
abstract granite
digital crypt
digital crypt
#

src.setting

viscid hornet
# digital crypt ok

its a wrapper around sqlite3 so go in this order:
sql -> sqlite3 -> asqlite

digital crypt
#

ohk

viscid hornet
abstract granite
viscid hornet
digital crypt
#

btw i feel like im very far behind in comparision to you guys, where did u learn all this from?

#

im assuming experience

viscid hornet
#

and just commitment

#

once you get in the water, swimming becomes a lot easier

digital crypt
#

Tho don't have much time as I'm also managing school

#

This is last year, I'm going to collage soon

viscid hornet
viscid hornet
abstract granite
#

I have 1 question

#

Why, for example, when I put ready.py in an events folder, it doesn't find it?

viscid hornet
#

basically it’s looking at everything NOT in folders when you write something normally

#

like open(“filename_here”) will check if its in that folder

#

to look for stuff in other folders you need to do folder.file

#

so if filename_here was in another folder, it would be parent_folder.filename_here

#

hope that makes sense for you ❤️

unkempt canyonBOT
#
The `pathlib` module

Python 3 comes with a new module named Pathlib. Since Python 3.6, pathlib.Path objects work nearly everywhere that os.path can be used, meaning you can integrate your new code directly into legacy code without having to rewrite anything. Pathlib makes working with paths way simpler than os.path does.

Feature spotlight:

  • Normalizes file paths for all platforms automatically
  • Has glob-like utilites (eg. Path.glob, Path.rglob) for searching files
  • Can read and write files, and close them automatically
  • Convenient syntax, utilising the / operator (e.g. Path('~') / 'Documents')
  • Can easily pick out components of a path (eg. name, parent, stem, suffix, anchor)
  • Supports method chaining
  • Move and delete files
  • And much more

More Info:

abstract granite
viscid hornet
slate swan
#

Depends on your files and folders

abstract granite
viscid hornet
#

so if its ./src/events/ready.py, that becomes from src.events import ready

abstract granite
#

Ok ok

#

Thx

sly hamlet
#

Who put this logo down inside my footer but when I do I just get the application. Did not respond in no error inside of my log

@app_commands.command(name='warn',
                       description="Warns a specified user.")
    @app_commands.checks.has_permissions(manage_roles =True)
    async def warn(self, interaction: discord.Interaction, user: discord.Member, *, reason: str = None):

            em = discord.Embed(color=0x7289da)
            em.add_field(name=f'Warn Successful', value=f'You have been warned in **{interaction.guild}** by **{interaction.user}** for `{reason}`')
            em.set_footer(icon_url="logo.png", text="Echo Discord Bot")
            await interaction.response.send_message(embed=em)```
viscid hornet
sly hamlet
#

So when I put in the icon URL into the footer the command no longer works. But when I take it out the command works when it doesn't work. All it says is did not respond to command

viscid hornet
#

ah i know what it is

#

icon_url takes a web link and “image.png” is not a website link

#

?tag file

novel apexBOT
#

This is not a Modmail thread.

viscid hornet
#

oops, forgot this isnt dpy

sly hamlet
#

So is there a way to do it without a web link?

viscid hornet
sly hamlet
#

thx

vapid parcel
#

Okay, so I have a simple issue, I have a calculator command, which uses eval, how can I make my bot not crash when someone does 9^9^9^9 or maybe something bigger? I don't want a limit on it where they can only have this amount of exponents, but I want it to return a custom error if the eval failed, but I don't want my bot to go offline either, how can I prevent this?

    @discord.ui.button(label='=', style=discord.ButtonStyle.green, custom_id="=", row=4)
    async def equal(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message("This button isn't for you. Just run the command yourself goober.", ephemeral=True)
            return

        if interaction.user.id == self.ctx.author.id and not self.disabled:
            expression = self.value.replace('x', '*').replace('÷', '/').replace('^', '**')
            try:
                try:
                    result = str(eval(expression))
                    self.value = f"{self.value} = {result}"
                    self.clear_on_next_input = True
                except Exception:
                    self.value = "The provided equation is invalid!"
                    self.clear_on_next_input = True
            except ZeroDivisionError:
                self.value = 'Infinity'
                self.clear_on_next_input = True
            except Exception as e:
                self.value = "The provided equation is invalid!"
                self.clear_on_next_input = True
            embed = await self.update_embed(interaction)
            await interaction.response.edit_message(embed=embed, view=self)```
fiery girder
#

and its an overall problem

paper snow
#

is there a Discord library available that is an actual API wrapper (closer to 1-to-1) and not a phat framework in which to nestle your little snippets of python and watch it play with them?

hushed galleon
paper snow
hushed galleon
paper snow
#

the ability to finely control the main run loop

#

So that I can have external functions trigger depending on the actual status of the bot instead of starting a second thread and giving it a stop flag with a try/finally, as well as have external functions cause the bot to do something without needing to break out to the rest api in the middle of a bot that's literally built in the gatewaybot class

viscid hornet
#

you might want a math tokeniser that can manually execute operations from a string as that way you can control limits from there: as 9^9^9 is already in the billions or even futher

#

try and find something online that will suit your needs

hushed galleon
# paper snow So that I can have external functions trigger depending on the actual status of ...

im kind of confused why a second thread is needed given that hikari uses an asyncio event loop, though curiously it doesnt look like they have a simple async alternative to GatewayBot.run() which is kind of weird - i would have assumed GatewayBot.start() would be that, but it just returns after the shards are connected, so i have to guess from the source code that user needs to call join() and close()...

well regardless, i don't have any other libraries in mind, but i would try to figure out if you can manage the asyncio event loop without using GatewayBot.run(), that way you can start your own asyncio task and do your own work while the event loop is running, something like: ```py
@contextlib.asynccontextmanager
async def start_gateway_bot(bot):
# Handles startup/teardown of a GatewayBot
await bot.start()
try:
yield
finally:
await bot.close()

# NOTE: this might not be sufficient, hence why I'm confused that
#       hikari doesn't have this - maybe worth a GitHub issue?

async def my_status_updater(bot):
# Do something every minute indefinitely, or whatever
while True:
await asyncio.sleep(60)
await send_status_update(...)

async def main():
async with start_gateway_bot(bot), asyncio.TaskGroup() as tg:
tg.create_task(bot.join())
tg.create_task(my_status_updater(bot))
# If an error occurs, TaskGroup will cancel join()/my_status_updater()
# and allow the bot to be cleanly closed
# (requires Python 3.11+)

asyncio.run(main())``` alternatively if you're interested in the technical details and you have the time, you can try writing your own gateway wrapper (see api docs and my attempt)

vapid parcel
# viscid hornet can you not just set a cap on the result size? and whats the issue with a quadru...

I fixed it to just use an API that will handle it all. The reason why 9^9^9^9 would crash the bot is because its just to big of a number, and will completely end the bot. The bot won't send an error or anything, on your console/terminal it says its still running even tho its not. It was just an eval issue, so I took out eval and used an api. This api does everything for me without me having to worry about its failing.

    @discord.ui.button(label='=', style=discord.ButtonStyle.green, custom_id="=", row=4)
    async def equal(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message("This button isn't for you. Just run the command yourself goober.",
                                                    ephemeral=True)
            return

        if interaction.user.id == self.ctx.author.id and not self.disabled:
            expression = self.value.replace('x', '*').replace('÷', '/').replace('+', '%2B')
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(f'https://api.mathjs.org/v4/?expr={expression}') as response:
                        if response.status != 200:
                            self.value = "The provided equation is invalid!"
                            self.clear_on_next_input = True
                        else:
                            result = await response.text()
                            self.value = f"{self.value} = {result}"
                            self.clear_on_next_input = True
            except Exception as e:
                self.value = "The provided equation is invalid!"
                self.clear_on_next_input = True
            embed = await self.update_embed(interaction)
            await interaction.response.edit_message(embed=embed, view=self)```
#

Then the command will look like this at the end, which I think looks pretty good!

#

Its like a literal calculator inside of discord, which is funny and cool at the same time, took me like 1-2 hours to do because of the eval stuff, which an api took over because its just easier that way.

viscid hornet
#

idk why i didnt think of doing something like this sooner

abstract granite
viscid hornet
viscid hornet
#

i say grab some paper and outline what your bot is and does. draw a spider diagram where all the features extend into other features

abstract granite
viscid hornet
viscid hornet
#

or libraries made by you

#

which congrats cuz thats a lot of work to make a whole library

abstract granite
viscid hornet
#

have your files structured like this:

  1. imports
  2. classes — this counts as views, buttons and anything else
  3. main cog code
  • abstracted functions
  • commands
  1. setup func
viscid hornet
# abstract granite Yeah

something i learned to save space is to list them like this:

import thing1, thing2, thing3, thing4

instead of like this:

import thing1
import thing2
import thing3
import thing4

viscid hornet
abstract granite
#

Ohh thx

viscid hornet
# abstract granite Ohh thx

i suggest the paper strategy because it gives you a visual representation of what your bot does or is supposed to do

vapid parcel
#

I did it because, you can always have a command that does calculations, but you would have to restrict like words, and so many other things, with this, you can't enter anything you want, you have to do what the buttons want!

abstract granite
viscid hornet
viscid hornet
vapid parcel
viscid hornet
vapid parcel
#

yeahh

#

its sad 😭

viscid hornet
#

what do AC and DC do?

vapid parcel
#

AC clears all

#

DC disables the calculator

viscid hornet
vapid parcel
#

ill just send video

viscid hornet
#

like turns it off?

viscid hornet
vapid parcel
abstract granite
vapid parcel
#

Just makes it not useable no more, but there is almost a timeout of 120 second (2 minutes), so just incase they don't disable it, it will do it on its own!

viscid hornet
vapid parcel
#

Yeah

viscid hornet
#

and then lower the timeout from 120s to like 45s

vapid parcel
#

I mean I could

viscid hornet
#

you dont really need a 2 minute time period 😭

vapid parcel
#

Maybe they wanna come back? GoofySkull

viscid hornet
vapid parcel
#

idk I put high time on it just incase

vapid parcel
viscid hornet
vapid parcel
#

lmao

#

real

viscid hornet
#

i like the pi button, nice touch

vapid parcel
#

So something like this?

viscid hornet
#

make the sq root blurple tho

#

cuz its not a number its an operation

vapid parcel
#

yeah

viscid hornet
#

and the obelus is pretty hard to see

#

swap it with a slash (“/“)

#

past that, no other improvements

#

what character did you use for the backspace?

viscid hornet
vapid parcel
viscid hornet
vapid parcel
#

Final product tho! Looks clean, thanks for all of the suggestions!

viscid hornet
vale wing
vapid parcel
vale wing
#

Oh alr then

vapid parcel
#

just the ANS button

vale wing
#

We had a command in bobux bot that looked good at pc version (5 rows of buttons) but on mobile it was just damn vertical buttons list

vapid parcel
#

lol

#

it looks good enough on mobile imo

#

Basically because they are all the same length in text thats mainly why

quick gust
#

veri cool

viral mica
#

guys anyone has created twitter bot recently?

vapid parcel
shrewd apex
#

cool stuff

viscid hornet
agile idol
#

anyone know to fix this?

naive briar
#

That's not how you make slash commands in discord.py 🫠

agile idol
naive briar
viral mica
viscid hornet
viral mica
viscid hornet
naive briar
#

This is a channel about discord bots, so I don't think there's any Twitter bot dev here pithink

viscid hornet
leaden olive
#

how could i fix that?

shrewd apex
#

reduce the embed description size

vale wing
agile spade
slate swan
#

nextcord for real GIGACHAD

leaden olive
#

I have a embed whose description always expands automatically when someone is warned, but since embed have a max length, i dont know how i can do this in the future now

agile spade
agile spade
#

Fields don’t count towards the description but they still add to the embed

leaden olive
#

yea and how can i automatically add a new field once someone is warned?

#

there has to be a max embed fields

hushed galleon
#

have you considered showing only the most recent warnings in your embed?

flat pier
#

or you can make a paginator

hushed galleon
#

im assuming its a persistent message given that the embed is "automatically updated", in which case giving paginator controls to everyone that can access it might get a bit awkward

agile spade
hushed galleon
#

but otherwise for temp/ephemeral embeds that'd be a good idea

halcyon fiber
#

hey guys can you guys help me for my assignment so i create a discord chatbot for these

  1. Identify suitable plants and provide advices on good practices on taking care of the plants;
  2. Monitor real-time plant growth conditions like temperature, amount of light intensity, soil moisture, pH level, with consideration of geographical and weather information;

but i use my command it didnt show the result I want

#

import discord
from discord.ext import commands
import requests

Define intents

intents = discord.Intents.all()

Initialize Discord bot with intents

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

Define API endpoints

PLANT_API_URL = "https://trefle.io/api/v1/plants"
WEATHER_API_URL = "https://api.openweathermap.org/data/2.5/"

Function to fetch plant information

def get_plant_info(plant_name):
# Make a request to the plant API
response = requests.get(f"{PLANT_API_URL}/plants/{plant_name}")
if response.status_code == 200:
return response.json()
else:
return None

Function to fetch environmental data

def get_environment_data(location):
# Make a request to the weather API based on location
response = requests.get(f"{WEATHER_API_URL}/weather/{location}")
if response.status_code == 200:
return response.json()
else:
return None

@bot.command()
async def plant_care(ctx, plant_name):
plant_info = get_plant_info(plant_name)
if plant_info:
care_advice = plant_info.get('care_advice', "No care advice available for this plant.")
await ctx.send(f"Care advice for {plant_name}: {care_advice}")
else:
await ctx.send(f"Sorry, I couldn't find information for the plant '{plant_name}'.")

@bot.command()
async def monitor(ctx, location):
environment_data = get_environment_data(location)
if environment_data:
# Parse environmental data and send to Discord
await ctx.send(f"Environmental data for {location}: {environment_data}")
else:
await ctx.send(f"Sorry, I couldn't retrieve environmental data for the location '{location}'.")

Run the bot

bot.run("discord token")

halcyon fiber
#

this

#

fucking doing for 2 weeks and even ask help from the damn ai still no fruit

quick gust
#

are u providing an access token?

halcyon fiber
quick gust
#

I believe the access tokens are free on that site, so you can just make an account there and get one if you want

halcyon fiber
quick gust
#

nice

dusk ermine
#

select_callback
if interaction.message.components[0].custom_id == "ticket_select":
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ActionRow' object has no attribute 'custom_id'

help me

slate swan
#

The first component is ActionRow and it doesnt have .custom_id attribute

pale zenith
#

need to acces the children, message.components[0].children[0].custom_id

swift siren
#

can you fetch user about me's using bot authentication ?

slate swan
slate swan
#

This will only work when its ActionRow component

#

When its Button or else it wont

hushed galleon
#

pretty rare to see message.components being used though... are you sure you couldnt set select.custom_id = "ticket_select" and add it to a persistent view instead?

pale zenith
#

oh wow I dind't read that properly. Definitely that ^^

cedar blade
#

.

viscid ridge
#

how do i give / commands an option?

#

like

music = f"video url or name"
and it gives me what they put in?

viscid ridge
#

ok but how do i

get the returned varible from a function?

slate swan
#

you get it as parameter to function

slate swan
#

whats the max amount of parameters slash commands can have as Optional inputs for discords UI?

vapid parcel
#

Anyone truly have a working Music bot using Lavalink?

#

I have tried for many days, and I feel like I have gotten no where, so if someone has a WORKING one, please let me know, its really annoying. I just can't get it to work in anyway. I got a working Lavalink server, just not a working bot I guess.

mighty terrace
#

how can i send a dm message to a user wich is given by user id using slash commands?

slate swan
vapid parcel
#

Couldn't get it working

#

so idk, I truly can't find one that works.

sick birch
vapid parcel
sick birch
#

well most sites like youtube and spotify dont let you do that so thats probably why

vapid parcel
#

You are allowed to do it, but it just breaks their ToS

sick birch
#

that means you aren't allowed to

vapid parcel
#

Yes I know 😭

#

But I am just still trying to get one to work

sick birch
#

and anyway, we don't really help with music bots here because of rule 5

vapid parcel
#

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

vapid parcel
#

I thought violate tos was only for discord?

sick birch
#

no we can't help you violate any other ToS either

vapid parcel
#

I didn't know it covered like overall, so thats my bad

#

alright, thats my bad, thought it only covered discord tos

vapid parcel
#

Does anyone know a good spot where people can review my bot and just do testing on it?

viscid ridge
#

friends

vapid parcel
#

Wish I had some GoofySkull

vapid parcel
#

Yeah

#

I need people to test and review it 😭

#

So thats why I am asking here to see if anyone knows a good spot for others to just test the bot.

viscid ridge
#

so uh erm.

#

why cant i invite my discord bot?

vapid parcel
viscid ridge
vapid parcel
#

How so?

viscid ridge
#

i changed it.

#

i forgot to update it in the discord

vapid parcel
#

this is all you would need

viscid ridge
#

not for voice usage. and message usage

vapid parcel
#

....

#

For sending messages, you use an INTENT.

viscid ridge
#

mhm

vapid parcel
#

and for voice all you would need is a voice permission which is inside of permissions, not scopes.

vapid parcel
#

No you do not 😭

vapid parcel
#

why you using applications.commands.permissions.update?

vapid parcel
#

thats not needed for slash commands either.

vapid parcel
#

Bro, I have a verified discord bot with slash commands... and it does not use that scope.

#

It only uses bot.

viscid ridge
#

ok then what is it?

vapid parcel
#

what is what?

#

The link?

vapid parcel
#

The rest is usually for like websites n other stuff. But since you are most likely doing everything inside of discord, you won't need that.

turbid condor
#

I'm not sure but it should be as many as you like

#

You can make all your params optional if u want to

slate swan
#

like if i wanna pass through an optional amount of parameters like 20 roles, would it work?

turbid condor
#

Should work but u should try and see

#

Since they are params so it shouldn't be a problem unless you are talking about buttons

#

Which is 25 for each msg

vapid parcel
#

I thought parameters were 20?

#

Parameters are 100% 20 or 25.

#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 63.options: Must be 25 or fewer in length.```
#

you will get this error if you go over 25.

slate swan
#

thank you! I actually just found out u need to send the parameters as snake_case or i got errors. weird.

vapid parcel
#

are you using dpy..?

#

what is snake_case...?

#

oh im slow GoofySkull

Simple google search helped me 😭

slate swan
#

lol

vapid parcel
#

Yeah you can't use spaces unless its like an Enum or Auto Complete I am pretty sure

slate swan
#

naw i tried js formatting

#
Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'limit_list' defined in function 'ModeratorTestSlashCommands.limit_list'
  In parameter 'roleTwo'
    name: Command name is invalid
vapid parcel
#

yeah

slate swan
#

once i swapped em to snake_case they worked lmao

vapid parcel
#

gotta do role_two or role-two

#

or just roletwo

#

But what you can do is, to make it look nicer..

#
from discord import app_commands

    @app_commands.describe(paramater='description')

#

so for an example you could just put 2 instead of role_two

#

and the describe will let you put a description for that paramater

slate swan
#

ohhhh

vapid parcel
#

which shows up above in slash commands.

#

if you want it to look nicer thats what I suggest, but thats up to you. either way the main goal is to have the bot work at the end lmao

abstract granite
#

How do I create buttons with Python?

vapid parcel
#

Actually, don't use that example

slate swan
vapid parcel
abstract granite
#

Ok

vapid parcel
#

yeah, the old one I just showed you is a little outdated in a way

vapid parcel
slate swan
#

like _1? or am I missing something

vapid parcel
#

wait can you not do numbers?

#

oh, I didn't know you needed 2 characters, that is my bad!! You can just do one, two, three instead of roleone, roletwo, rolethree?

#

I didn't know you needed 2 characters for a parameter to work, I am sorry.

vapid parcel
# abstract granite Ok

Did you ever get those buttons working? Or are you still needing help, because I can always help you!

slate swan
vapid parcel
#

or

#

you could do r1 as role 1

#

but either works, glad I could help lol

keen lynx
#

Not always but some specific cmd output print 2 times.this does not happen with all cmd just with few commands. idk whats the issue.

dusk ermine
#

if interaction.select.custom_id == "ticket_select": AttributeError: 'Interaction' objecy has no attribute 'select'

naive briar
#

Shocking

vapid parcel
#

await bot.process_commands(message)

if you have this in an on_message event, then you will have it do it twice.

keen lynx
vapid parcel
#

You are using cogs right?

#

Each cog can have its own on_message event, meaning not all of your cogs have an on message event, but any cog with an on message event and have await bot.process_commands(message) it will send twice

#

Thats just from expirence tho!

vapid parcel
#

@keen lynx did you fix it, or is it still happening?

keen lynx
vapid parcel
#

you have no reason to have it in main.py, you honestly don't need that

keen lynx
#
@client.event
async def on_message(message, **kwargs):
    #message.content = message.content.lower()
    msg = message.content.lower()

    if message.author == client.user:
        return

    if message.content.startswith("Sudo "):
        message.content = message.content.replace("Sudo ", "sudo ")
 await client.process_commands(message)
naive briar
#

!d discord.ext.commands.Bot - you can turn case_insensitive on to make the bot ignore cases for the prefix/command, so you don't have to do it manually

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
vapid parcel
keen lynx
vapid parcel
#

I have never needed

bot.process_commands(message)

keen lynx
# vapid parcel np

it worked. yeah no need of it

prefixes = ["Sudo ", "sudo "] # Add all your prefixes here
super().init(commands.when_mentioned_or(*prefixes)

vapid parcel
#

Mhm

#

You will never need that in your bot

#

Unless its an all 1 one file, then you will never need it

sturdy fractal
#

Can we log deleted media files ( videos , pdf , exe , XML , )
Ik we can log images

naive briar
#

Don't try to access attributes that doesn't exist

#

Where did you get the interaction.select from anyway?

dusk ermine
naive briar
#

Where did you get the idea to try and access a select attribute of interaction? That doesn't exist

#

Maybe you're mixing different libraries?

dusk ermine
jade frost
#

1-is there free good api, 2-can build discord bot with python?

sudden dirge
#
  1. yes, there is nextcord, discord.py, pycord and many more
jade frost
#

not bot need api?

sudden dirge
#

are you taking about free hosting for the bot?

jade frost
#

can bot work in discord server-channel for 24 without my pc

sudden dirge
#

if you don't want to use your pc to run the bot, there are a few, decent-ish free hosting - but if you want guaranteed 24/7 (not including server down time for upgrades or whatever) you should look into a paid hosting service

jade frost
#

and may i ask about something, why bots not run on channel it self inside the discord servers?

#

its logic that channels work on pc servers like bots

sudden dirge
#

discord doesn't host bots, it's up to the developer to keep the bot online

sudden dirge
jade frost
#

you give me your time, and care ,and helped me🙏

sly hamlet
#

Is there a discord.py updated that does error handleing different I can't see errors in my console now

naive briar
#

Are you running the bot with the .run method? If not, you'd need to setup logging

#

!d discord.utils.setup_logging - or use this convenient function

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2.0.
sly hamlet
#

This looks fun

leaden olive
#

does anybody know why the message isnt "ephemeral"

signal turret
#
from discord.ext import commands
import random

bot = commands.Bot(command_prefix='.', intents=discord.Intents.default())
laby = {1 * 100}


@bot.event
async def on_ready():
    print('Ready')

@bot.comamand()
async def ping(ctx):
    await ctx.send(random.randint(laby))


bot.run('')```
sly hamlet
#
@bot.event
async def on_member_join(member):
    channel=bot.get_channel(924384859923837018)
    em=discod.Embed(title="test", descriptipn=f"{member.mention}")
    await channel.send(embed=em)```I have this welcome message doesn't seem to work and I've get no error inside of my log. Any thoughts? I'm out of ideas
ocean spindle
#

async def is_it_up(interaction, site: str): if not site.startswith("https://") and site.startswith("http://"): if site.startswith("www."): site = f"https://{site}" else: site = f"https://www.{site}" try: r = httpx.get(site, timeout=5) #if the status code is 200 then the URL is up if r.status_code == 200: await interaction.response.send_message(f"{site} is up :)") #if the status code is not 200 then the URL is not up except Exception: await interaction.response.send_message(f"{site} is down :(")

So i'm trying to make a command to check if a website is up, and I want it to allow both http:// and https:// sites, it worked fine when i did it on command line but now it's not working

#

it only works for https://

vapid parcel
vapid parcel
#

If you change that, then it should be fixed!

vapid parcel
# ocean spindle ` async def is_it_up(interaction, site: str): if not site.startswith("https:...
async def is_it_up(interaction, site: str):
    if not site.startswith("https://") and not site.startswith("http://"):
        if site.startswith("www."):
            site = f"https://{site}"
        else:
            site = f"https://www.{site}"
    try:
        r = httpx.get(site, timeout=5)
        # if the status code is 200 then the URL is up
        if r.status_code == 200:
            await interaction.response.send_message(f"{site} is up :)")
        else:
            await interaction.response.send_message(f"{site} returned status code {r.status_code}, it might be down :(")
    except Exception:
        await interaction.response.send_message(f"{site} is down :(")
vapid parcel
ocean spindle
vapid parcel
#

Okay!

#

Hope it works!

vapid parcel
vapid parcel
ocean spindle
vapid parcel
ocean spindle
#

but thanks

vapid parcel
#

Okay, just a recommendation!

#

Alright, I think no one else needs help.

fading marlin
# vapid parcel Also, I recommend using aiohttp! Its a better library than httpx.

^ it's not just better, it's async, which means it doesn't block your code. Your bot will freeze for the amount of time httpx.get takes to yield, which could cause problems. Further, you should be careful with how you handle user-inputted URLs. There's always that not-so-nice user that might try to do something malicious and screw you over, @ocean spindle.

vapid parcel
#

Also, they should probably open the links within a save enviroment, just incase.

#

Or make the command developer/owner only.

fading marlin
#

httpx itself also includes an async client

vapid parcel
#

I did not know that.

#

Ive always used aiohttp so i guess I never looked into that. But nice to know, I just think aiohttp is really good.

fading marlin
vapid parcel
#

lmao, thats fair

ocean spindle
#

should I run my bot on a VM?

vapid parcel
#

What you could use is

#

uptimerobot which will do the stuff for you, it will check if the website is up or down

#

Which is ran in a save environment.

#

or isitup.org something like that would work I think

#

I think isitup.org was removed actually, so I guess use uptimerobot

ocean spindle
vapid parcel
#

per?

#

They are a good website

ocean spindle
#

ngl I'll prolly just remove the command for now

vapid parcel
#

alr lol

ocean spindle
#

but my issue is whenever I remove a command it can't leave

#

like it's stuck there

vapid parcel
#

wdym?

#

just sync the commands again?

ocean spindle
#

here's the problem

#

i tried that

vapid parcel
#

then refresh your client

#

and it should be gone

ocean spindle
#

like refresh in what way?

vapid parcel
#

you are on pc?

ocean spindle
vapid parcel
#

do ctrl + r

#

it will refresh discord

#

then the command should be gone :)

ocean spindle
vapid parcel
#

are you syncing?

#

You need to sync the command, then refresh discord

#

ill send a video of this working 😭

ocean spindle
#

in the on_ready function?

vapid parcel
#

my mic was on, oops lmao

vapid parcel
#

also, never put anything inside of on ready :)

ocean spindle
vapid parcel
#

Its bad

#

Are you using cogs tho?

ocean spindle
#

no

vapid parcel
#

do you know cogs?

ocean spindle
#

nah

vapid parcel
#

This teaches cogs, sub commands, hybrid commands, prefix commands, buttons, drop down menus, and more.

sick birch
vapid parcel
sick birch
vapid parcel
#

For buttons n stuff?

hushed galleon
hushed galleon
vapid parcel
sick birch
sick birch
vapid parcel
#

I didn't really know, I thought it didn't effect it

hushed galleon
vapid parcel
#

I mean, that code runs perfect, but I am a little confused on what parts you guys want me to change

#

Are you guys talking abt the file names?

hushed galleon
#

im not saying you should change anything cause it works fine, its just a bit unconventional

#

"conventional" package/module naming would be snake_case

vapid parcel
#

Oh, okay, I was just a little confused on if you guys were trying to say it would effect the functionality of the bot or what lol.

vapid parcel
hushed galleon
#

nope, just how your imports look

vapid parcel
#

oh okay

#

Was a little confused for a second, sorry about that.

hushed galleon
vapid parcel
#

Yeah thats what had me confused, I was oh shit is this gonna cause issues in the future?

#

But glad you cleared it up lol, kinda had me worried on something I never knew or thought about.

sick birch
sly hamlet
# vapid parcel No problem!

still cant get it to work py @bot.event async def on_member_join(member): role = discord.utils.get(member.guild.roles, id=924252667809779733) await member.add_roles(role, atomic=True) channel = bot.get_channel(924384859923837018) em = discord.Embed(title="Welcome", description=f"Hello {member.mention}, Welcome to", color=0x00ff00) em.set_footer(text=f"test") await channel.send(embed=em)

vapid parcel
#

just add this

#
@bot.event
async def on_member_join(member):
    try:
        role = discord.utils.get(member.guild.roles, id=924252667809779733)
        await member.add_roles(role, atomic=True)
        channel = bot.get_channel(924384859923837018)
        em = discord.Embed(title="Welcome", description=f"Hello {member.mention}, Welcome to", color=0x00ff00)
        em.set_footer(text=f"test")
        await channel.send(embed=em)
    except Exception as e:
        print(f"{e}")
#

also what is atomic?

sly hamlet
vapid parcel
#

atomic=True

#

what is that?

sly hamlet
vapid parcel
sly hamlet
#

Also, that doesn't return back to anything

vapid parcel
#

So is the role id correct?

#

and is the channel correct?

sly hamlet
#

Yes

vapid parcel
#

Here, let me join the testing server and Ill help you?

#

Ill use my own bot for testing tho?

sly hamlet
vapid parcel
#

okay, just send the invite in my dms

vapid parcel
hushed galleon
# sick birch i'm curious, though - how are you doing your migrations? is it all in the `docke...

yes, i was experimenting with having the database container do its own migrations instead of running them from the app - it was kind of awkward and still left me the question of how i would deal with different branches... i remember reading something about simplifying migrations to dev -> staging -> prod without tracking a bunch of ordered scripts, but i cant for the life of me find that article again

sick birch
naive elbow
#

guys how i can mention all members with bot on my server

golden portal
#

you should just use everyone mention instead of doing individual mention

golden portal
#

so mass DM? you're gonna get ratelimited doing that

vapid parcel
#

thats against tos.

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.

naive elbow
vapid parcel
naive elbow
#

ok

vapid parcel
#

Its against ToS to do mass dm.

naive elbow
#

it’s ok

glass bluff
#

how are you even supposed to learn

#

how to write discorad bots

#

i get confused in the documentation thing

vapid parcel
#

YouTube, Documentation, Templates, People

glass bluff
#

oh yeah thats true

#

but like does discord expect you to just look through the documentation

#

and learn from there generally

vapid parcel
#

idk

#

best spot to learn

leaden olive
mighty terrace
#

how can i tell the bot so it automatically reacts on its own messsage after he sent it?

#

i tried looking it up but the way i found it everywhere is not working

pale zenith
mighty terrace
#

thats what i kinda tried but since im working with @bot.tree.commands i used interaction

pale zenith
#

after you send your .response,
msg = await interaction.original_response()

#

since .response.x methods always return None

mighty terrace
#

i think i understand thank you

sick birch
#

doesn't mean you can't learn it if you're a beginner, though. it will just be harder

viscid hornet
viscid hornet
viscid hornet
quick gust
#

they both allow you to use sqlite asynchronously ¯_(ツ)_/¯

midnight oracle
#

Hya, a little question here. I have uploaded the ffmpeg.exe file to my bot repo, what should I do in the settings.py file to define the dir of the ffmpeg ans use it from there in the code? Idk if I explain myself xd

#

I mean, how do I run the exe with the config I have already defined in a list for the ffmpeg using the EXE in the repo

vapid parcel
viscid hornet
viscid hornet
midnight oracle
#

it's for a personal music bot

viscid hornet
midnight oracle
#

Nope, I want to host the bot

#

buut i need to use the ffmpeg exe that i uploaded to the repo insted of the PC's one bc it is being hosted

#

so the "server" does not have ffmpeg installed

#

Idk if I'm explain myself. Am I? xd

balmy hornet
#

noted. after fighting with boto3, and trying later with aioboto3 and aiobotocore for half the day yesterday trying to get asynchronous AWS integration working... I finally got it working after abandoning all hope w/ that and using asyncio.create_subprocess_exec() and a cli tool.

Don't use aioboto3 lol, it lies... it LIES!!! it killed my bot whenever it ran lol. Cut off its blood supply and left it lifeless. :(

viscid hornet
viscid hornet
#

im not understanding

balmy hornet
#

nah this is just documenting for future peeps who do similar stuff. Ik when I'm doing something and having issues I'll often use Discord's search to see if anyone else has had a similar issue. This came up blank so I was on my own. Hopefully the next person won't be. :)

vapid parcel
sick birch
#

i believe you can just do that over HTTP

viscid hornet