#discord-bots

1 messages · Page 293 of 1

white crown
#

Why does that happen, with a discodd.iu The !button does not work but with discord.txt the button works but it gives the failed interaction?

slate swan
#

whats the best way to edit an embed message sent by the bot?

#

im currently doing await interaction.response.edit_message(view=self)

#

but when the message gets edited, it disappears from a while from discord, just a bit, few miliseconds

#

but ive seen other bots without this small delay

white crown
slate swan
#

both

#

via paste would be great

#

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

slate swan
#

Hello my bot no longer responds to my command I don't know why 0 error message

import discord
from discord import app_commands
import asyncio
import random
import discord.member
from discord.ext import commands

intents = discord.Intents.all()
intents.members = True

client = commands.Bot(command_prefix="+", intents=intents)
client.remove_command('help')

@client.event
async def on_ready():
print('Bot ready')

@client.command()
async def owner(ctx):
print("owner")
await ctx.send("Halycon !")

client.run("token")

slate swan
#

No

#

does the "bot ready" get printed?

white crown
white crown
#

You could have used it to see if your Owner command was working

fading marlin
# white crown https://paste.pythondiscord.com/VMKQ

Callbacks from buttons have the signature of (self, interaction). It's better to subclass and create your views the OOP way to prevent these sorts of issues, rather than what you're currently doing with the assignments.

white crown
# fading marlin Callbacks from buttons have the signature of `(self, interaction)`. It's better ...
from discord.ext import commands
from discord.ui.button import Button
from discord.ui.view import View

class ButtonView(View):
    def __init__(self, ctx):
        super().__init__()
        self.ctx = ctx
        self.add_item(Button(style="primary", label="Haz clic aquí"))

    async def interaction_check(self, interaction):
        return interaction.user.id == self.ctx.author.id

    async def on_timeout(self):
        pass

    async def on_button_click(self, interaction, button):
        await interaction.response.send_message("¡Has hecho clic en el botón!")

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

    @commands.command()
    async def boton(self, ctx):
        view = ButtonView(ctx)
        await ctx.send("Presiona el botón:", view=view)

async def setup(bot):
    await bot.add_cog(BotonCog(bot))```
hasty pike
slate swan
#

example how to add buttons to view

hasty pike
#

Bro didn't use decorator

slate swan
#

what did you try??

white crown
#

The example you sent me from git

white crown
#
import discord
from discord.ext import commands

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

    @commands.command()
    async def boton(self, ctx):
        class Confirm(discord.ui.View):
            def __init__(self):
                super().__init__()
                self.value = None

            @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
            async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
                await interaction.response.send_message('Confirming', ephemeral=True)
                self.value = True
                self.stop()

            @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
            async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
                await interaction.response.send_message('Cancelling', ephemeral=True)
                self.value = False
                self.stop()

        view = Confirm()
        await ctx.send('Do you want to continue?', view=view)
        await view.wait()
        if view.value is None:
            await ctx.send('Timed out...')
        elif view.value:
            await ctx.send('Confirmed...')
        else:
            await ctx.send('Cancelled...')

def setup(bot):
    bot.add_cog(ButtonCog(bot))
slate swan
#

...

#

you are not supposed to just copy paste it and expect it to work

hasty pike
#

You don't need decorator inside command

#

Decorator is needed in class

slate swan
#

first of all never nest a class inside other class

hasty pike
#

Oh he actually nested a class inside a function, i didn't notice at first

#

Worse practice

slate swan
#

put it outside

#

then check how it works

slate swan
#

Can someone help me make a timeout command?

slate swan
slate swan
#

can you help? @slate swan pithink

#

let me know if you understand everything in here

white crown
#

I will try what you said pithink

slate swan
#

it requires many advanced topics like OOP, decorators, async/await syntax

drifting arrow
#

with app_commands.choices, does the value need to be a number?

true_false = [
        app_commands.Choice(name=True, value=1),
        app_commands.Choice(name=False, value=2)]

or can I put whatever?

#

like say I want the value for True to be "Happy Days" instead of 1, can I?

golden portal
#

it supports int, str, float

drifting arrow
#

neat

hushed galleon
drifting arrow
#

So I can do: async def usersettings(self, interaction: discord.Interaction, setting: app_commands.Choice[int], option:bool):?

hushed galleon
#

presumably yes, though i havent seen what a boolean option looks like

unkempt canyonBOT
#

discord/app_commands/transformers.py line 713

bool: IdentityTransformer(AppCommandOptionType.boolean),```
drifting arrow
#

Im currently fighting a different issue atm lol

#

OH LOL

#

figured it out

shrewd apex
#

thats what shows up

hushed galleon
#

neat

shrewd apex
#

in the options

#

mhm

worldly harbor
#

yo guys, im pretty much at 0 when it comes to dsicord bot dev, i've done py for a few years now (althoug have baerely coded in a few months ive basically forgotten everything)
what resources do yall recommend me to start with? ty

vocal snow
worldly harbor
#

thank you 🙏

vocal snow
eager ridge
#

can someone help me

#

i get this error on every bot what i made

buoyant quail
#

Show output of

import discord
print(discord.__version__)
eager ridge
#

wut

turbid condor
eager ridge
eager ridge
turbid condor
#

Update it to latest

eager ridge
#

nah then

turbid condor
eager ridge
#

will "from discord_slash import SlashCommand" not work

turbid condor
eager ridge
#

yea thast why i need to use old lib

turbid condor
#

Instead u should dpy in built module

eager ridge
#

on wich lib work "from discord_slash import SlashCommand"

turbid condor
turbid condor
#

You can check how to create slash commands in dpy in above gist

eager ridge
#

wich is better

discord-py-interactions
or
discord_slash

" for slash cmds "

visual island
eager ridge
#

what should i use ?

eager ridge
buoyant quail
#

You was answered like ten times that slash commands are already built into discord.py
Also you can try disnake or pycord if you don't like discord.py so much

visual island
eager ridge
eager ridge
buoyant quail
#

Then use what you like. But we can't really help with it

eager ridge
#

wich py version should i use for slash cmds with discord.py

visual island
buoyant quail
#

=2.0

#

but the latest is usually better

eager ridge
slate swan
#

Python 3.8, yes

eager ridge
#

and not python

slate swan
#

wich py version should i use for slash cmds with discord.py

#

which python version
krShrug

eager ridge
#

💀

slate swan
#

I mean, you asked the question krShrug

eager ridge
#

`import discord

class DMBot(discord.Client):
def init(self, token):
super().init()
self.token = token

async def on_ready(self):
    print("Bot ist bereit!")

async def on_message(self, message):
    if message.author == self.user:
        return

    if message.content.startswith("!dm"):
        recipient = message.mentions[0]
        message_content = message.content[4:]

        await recipient.send(message_content)

        print(f"Nachricht an {recipient.name} gesendet: {message_content}")

def main():
token = YOUR_TOKEN_HERE

dm_bot = DMBot(token)
dm_bot.run()

if name == "main":
main()`

#

like its not work

#

if i try to open it, its autoclose with out a error

#

ps : i am new in developing bots

#

oufff

#

guys help me out i am stuck

buoyant quail
#

Bot doesn't take token, but run does

#

intents are required argument for bot

#

And you will get an error by running this. It can't just autoclose

#

If it autocloses, it seems you are trying to open it with just a double click

errant kettle
#

Guys, is there any way that whenever someone sends an email I would setup somehow an integration and it would send me a message on discord as well? Ik it is kinda a stupid question 😄

slate swan
#

Yes

errant kettle
slate swan
#

By using Google on how to interact and use SMTP servers

formal basin
#
sws = clean_message2.replace(" ", "")
    allowed_words = set(['**1**'])
    banned_words = "|".join(map(re.escape, profanity.CENSOR_WORDSET - allowed_words))

    # Find if any banned words are in the message
    if re.search(banned_words, replacespaces(replacespecialcharacters(replaceDoubleCharacters(sws))), re.IGNORECASE):
        key = f'antibadwords:{message.guild.id}'
        if r.exists(key):
            await message.delete()
            embed = discord.Embed(title="No bad words allowed", description="Please refrain from using inappropriate language.")
            embed.set_footer(text="Censored by better-profanity")
            log = r.get(f"logs:{str(message.guild.id)}")
            await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
            embed = discord.Embed(title="Message Deleted", description=f"{message.author.mention}'s message was deleted.")
            embed.add_field(name="Reason", value="Contained bad words.")
            embed.set_footer(text="Censored by better-profanity")
            log2 = int(log.decode("utf-8"))
            logging = client.get_channel(log2) or await client.fetch_channel(log2)
            await logging.send(embed=embed)
            print(f"Bad word detected. Logs: {message.guild.id}")
```this code is deleting strings with bad words with no spaces for example its deleting "f***hi" i dont want it to to delete that
#

i would want it to delete f** hi

#

not f***hi

golden portal
#

just dont replace the space with empty string then at the top?

left dew
#

can i have a tasks.loop within a button class?

slate swan
left dew
slate swan
#

why does it has to be done in a loop

left dew
#

i cant think of another way to do it

slate swan
#

well you can do mytask.start() on button click

#

and then .cancel() or .stop() or other action

left dew
#

but within that loop im gonna be needing some stuff from my database. and i am going to need to use WHERE ... so that the info i get from the databse corresponds to the right users. i dont kniw how i'd do this

slate swan
#

.start takes arguments to pass to task

#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
left dew
#

so i could do mytask.start(interaction.channel.id)?

#

ohh i see

nova junco
#

Is there a site that can guid me through to make a bot with moderation stuff

#

etc

slate swan
#

Nope

left dew
slate swan
#

However, there are lots of websites, especially the documentation, which teach you the basics and can help you find the things you need

slate swan
buoyant quail
left dew
#

ok great

slate swan
#

Unless you're actually using them

left dew
slate swan
#

No

left dew
#

i can just do my_loop()?

slate swan
#

No

left dew
#

uh

slate swan
#

First thing you learn about functions, their parameters

nova junco
#

Is there a guide on making a discord bot in python??

left dew
slate swan
#
def blah(myAwesomeParameterWithoutDotsOrTryingToGetAnAttribute):
    print(myAwesomeParameterWithoutDotsOrTryingToGetAnAttribute.nowICanGetItsAttributes)
nova junco
#

Is there a guide on making a discord bot in python???????????

slate swan
#

Would you mind stop spamming your question that you can search on Google yourself??????????????????????????????????????????????????

nova junco
#

i cant find anything and sorry for spamming

slate swan
#

lmfao that's straight up a lie

left dew
nova junco
#

it just tells me how to turn on a bot

left dew
slate swan
#

✨ By using that parameter ✨

left dew
#

so channe1_id?

buoyant quail
#

!e ```py
def my_func(x):
print("yay, i got x:", x, "!!!")

my_func(123)

unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

yay, i got x: 123 !!!
buoyant quail
#

you can name it anything you want

slate swan
left dew
buoyant quail
#

if you will pass it to the start

slate swan
slate swan
left dew
#

ok

nova junco
left dew
slate swan
left dew
#

can i use .stop within the tasks.loop?

slate swan
#

tias

slate swan
slate swan
#

but i guess they too busy to correct it

slate swan
#

There, maybe a click is faster bravemmlol

#

i just told them there is a bug and forgot they forgot ducky_sus

#

Probably want to squash and merge PRs so that you don't always have 2 commits filling up for nothing

#

there you go

shrewd apex
#

😳

#

my bad my bad

slate swan
nova junco
#

how do i give my bot a prefix

buoyant quail
#

pass command_prefix to it

#

!d discord.ext.commands.Bot

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.
buoyant quail
#

it's required tho
you couldn't skip it

nova junco
nova junco
buoyant quail
#

It's giving the prefix there

nova junco
#

?

nova junco
buoyant quail
#

Context instance
it's always given to the prefix commands by discord.py library

#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
nova junco
nova junco
slate swan
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
slate swan
#

!d discord.User.send

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

Sends a message to the destination with the content given.

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

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

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

The way to send a message to a user based on its ID

#

First you get a user object

nova junco
#

can you help me

slate swan
#

After that you use the send method on it to send a message

naive briar
#

They're helping

slate swan
#

I already helped you, those are the two functions you need

naive briar
nova junco
#

which one do i type in first

nova junco
#

oki

slate swan
nova junco
#

should i make all commands in one file or multiple

#

how would i link the files

slate swan
#

Use Cogs

#

If you have one command, not really necessary

violet anvil
#

Hi

nova junco
slate swan
#

If you want to make the average moderation/multipurpose bot that exists already in 48292728 copies with all the same pointless commands, then you likely want to use cogs as mentioned above

slate swan
#

Use cogs if you feel it's necessary

nova junco
#

how do i add all those codes

#

am strugglingon that

hollow zinc
slate swan
slate swan
nova junco
#

uh ok

slate swan
lament depotBOT
slate swan
#

its on the way

hollow zinc
#

Ohh

nova junco
#

this is so hard bruh

slate swan
#

It's called OOP and is something you must know, so if you don't know it - you're looking at the wrong project to work on

#

As mentioned before multiple times, it's a library for advanced developers

violet anvil
#

Hay guys 🙏

slate swan
#

Yes

#

yeah

#

you do that like for a normal channel

#

A forum thread is a normal channel

#

!d discord.Thread.send

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

Sends a message to the destination with the content given.

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

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

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

So you can send like you'd do in any other channel

violet anvil
#

I am a bignner in python3

slate swan
violet anvil
plain pollen
#

@formal basin so, you want a cooldown on the message filtering? what would that entail?

#

would only every couple messages get filtered?

formal basin
plain pollen
#

how's it flagging too many times?

#

that's what i don't understand

formal basin
#

at once

plain pollen
#

what do you want it to do instead though? if you don't want it to be filtering every message, then which messages do you want to be filtered?

austere prairie
#

So you want to prevent users from sending messages too quickly?

violet anvil
#

Hay I am a. Bignner in python3

slate swan
violet anvil
plain pollen
plain pollen
#

why is the bot dealing with "too many messages at once" a bad thing?

violet anvil
#

@slate swan Wow 😲😳

formal basin
#

i dont make the rules

violet anvil
naive briar
#

Me when synchronous code in asynchronous environment:

formal basin
#

its because of regex

#

regex is a libary

#

and libaries have limits i think

naive briar
#

Limit of what?

plain pollen
# formal basin idk the heartbeat gets blocked

hrmm, that sounds like the regex check is taking too long, and so blocks for longer than it should - so then when discord tries to contact the bot to see if its still running (the "heartbeat"), it gets a super late response

slate swan
violet anvil
formal basin
slate swan
slate swan
plain pollen
#

how big is this list of banned words, can i ask?

formal basin
violet anvil
formal basin
#

maybe 912 or 907

#

somwhere there

slate swan
buoyant quail
#

Not for testing something

slate swan
naive briar
#

To be honest, I've mostly made bots to visualise something I made 🐈

violet anvil
formal basin
plain pollen
# formal basin over 900

hrmm okay
well, obviously since its taking too long to run the check, the first thing i'd do is see if there are any ways to speed this function up

#

could you paste the whole on_message listener?

plain pollen
#

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

formal basin
#

ok

thin raft
formal basin
slate swan
#

👍

slate swan
cloud dawn
#

@slate swan with the masterclass why is tested on python 3.9 and saying on the site it's 3.8+?

austere prairie
plain pollen
# formal basin https://paste.pythondiscord.com/IR2Q

that emoji-cleaning code looks a little more complex than it needs to be - you're running emoji.emojize, just to then convert those emojis back to their words, and then to further convert the words back into just letters

thin raft
formal basin
#

but how would you get the letter

slate swan
thin raft
unkempt canyonBOT
#

.github/workflows/format-and-lint.yml line 21

python-version: '3.9'```
formal basin
formal basin
#

but how will it get the letter from the message?\

thin raft
#

did you wrote that code?

formal basin
thin raft
#

write it by yourself and then ask for help :p

naive briar
plain pollen
#

IIRC, the message content just already contains emojis in their emoji form, rather than the :emoji: form, so that emoji.emojize step isn't doing much
then on top of that, your chain of .replaces could be replaced with a .translate, to map all those regional indicator emojis straight to the letters they represent

unkempt canyonBOT
#

mkdocs.yml line 57

- https://docs.python.org/3.9/objects.inv```
shrewd apex
#

we can change it in the config file

cloud dawn
shrewd apex
#

it lints and formats for version 3.9

#

tbh thats the oldest version of python i have used so far 😅 i did use 3.6 with some ubuntu default installs but that hardly counts

#

most of my projects range from 3.9 - 3.11

slate swan
#

3.12 💪

cloud dawn
#

Why is the masterclass even suggesting at least 3.8+ 😢

shrewd apex
#

were there any huge changes from .8 -> .9 ?

cloud dawn
#

Just force them to use 3.11

shrewd apex
shrewd apex
cloud dawn
shrewd apex
#

tru

slate swan
#

wait wait since discord.py is 3.8+ why you tell them to have python 3.9 or above xd

shrewd apex
#

for their own good

cloud dawn
#

lmao

shrewd apex
shrewd apex
#

feel free to make edits on second note tho

slate swan
cloud dawn
#

The thing that is bothering me the most is the way the Python installation is explained. Just use Brew, apt-get (curl) and Chocolatey. @slate swan

plain pollen
# formal basin hm ok

i think instead of all that, you could do something like this: ```py

a dictionary which maps the regional indicator emoji codepoints to their regular character codepoints

the numbers sorta look magic, but they work - you can poke around and figure how how this works by looking at what the result of chr(0x1f1e6) and chr(0x41) is

emojis_translation_table = {e: c for e, c in zip(range(0x1f1e6, 0x1f1ff), range(0x41, 0x5a))}

@client.listen()
async def on_message(message):
sws = message.translate(emojis_translation_table)

cloud dawn
formal basin
cloud dawn
#

!e print({e: c for e, c in zip(range(0x1f1e6, 0x1f1ff), range(0x41, 0x5a))})

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

{127462: 65, 127463: 66, 127464: 67, 127465: 68, 127466: 69, 127467: 70, 127468: 71, 127469: 72, 127470: 73, 127471: 74, 127472: 75, 127473: 76, 127474: 77, 127475: 78, 127476: 79, 127477: 80, 127478: 81, 127479: 82, 127480: 83, 127481: 84, 127482: 85, 127483: 86, 127484: 87, 127485: 88, 127486: 89}
cloud dawn
#

That's an interesting way to uhh write numbers.

cloud dawn
#

😇

severe sonnet
#

what kind of permission am i missing?

ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\User\Documents\GitHub\RP-Utilitites-Beta\cogs\ActionCog.py", line 42, in on_message
    webhooks = await message.channel.webhooks()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\channel.py", line 564, in webhooks
    data = await self._state.http.channel_webhooks(self.id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
slate swan
#

Whatever you're trying to do at line 42 in the file ActionCog.py

#

!d discord.TextChannel.webhooks

unkempt canyonBOT
#

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

Gets the list of webhooks from this channel.

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

docs once again are your hero

shrewd apex
shrewd apex
slate swan
#

They're just numbers in the end krShrug

shrewd apex
#

true

slate swan
#

You can use them as a replacement to numbers anywhere

#

even could use octal system if you wish

shrewd apex
#

yeah just didnt know u could pass them to range like that

shrewd apex
slate swan
shrewd apex
#

mhm

cloud dawn
#

@shrewd apex Any way to run the site locally? Never worked with mkdocs a lot.

slate swan
shrewd apex
formal basin
slate swan
#

or if you use poetry then portry run mkdocs serve

formal basin
#

you can do message.content

slate swan
#

!d str.translate

unkempt canyonBOT
#

str.translate(table)```
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via `__getitem__()`, typically a [mapping](https://docs.python.org/3/glossary.html#term-mapping) or [sequence](https://docs.python.org/3/glossary.html#term-sequence). When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return `None`, to delete the character from the return string; or raise a [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) exception, to map the character to itself.

You can use [`str.maketrans()`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) to create a translation map from character-to-character mappings in different formats.

See also the [`codecs`](https://docs.python.org/3/library/codecs.html#module-codecs) module for a more flexible approach to custom character mappings.
slate swan
#

its a string method

formal basin
slate swan
#

!e print(type(0o456))

unkempt canyonBOT
#

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

<class 'int'>
shrewd apex
cloud dawn
slate swan
#

Though to be fair I prefer to use hex when it makes sense, e.g. dealing with memory etc.

shrewd apex
#

mhm

#

assembly

slate swan
#

never used octal system though

violet anvil
#

Hi

shrewd apex
#

hex and binary most used

formal basin
#

@plain pollen its still heartbeat blocked. But it is a little faster

slate swan
violet anvil
slate swan
shrewd apex
slate swan
violet anvil
shrewd apex
#

since the gateway client for heartbeat runs in another thread

#

so you are probably doing some blocking task

slate swan
formal basin
slate swan
#

I mean system permissions, like file system permissions

shrewd apex
#

unix file perms

slate swan
#

yeah

severe sonnet
#

it needs manage_webhooks

#

how do i enable it by code?

slate swan
#

you need to have such permission

#

Permissions are in server settings

violet anvil
#

Anyone tell me the best course to learn python.

shrewd apex
slate swan
unkempt canyonBOT
#
Resources

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

shrewd apex
#

u should check for blocking tasks

slate swan
slate swan
formal basin
violet anvil
shrewd apex
#

time.sleep(60)

slate swan
shrewd apex
#

anything that blocks the main thread

slate swan
#

blocking code 😵‍💫

formal basin
shrewd apex
#

like pillow tasks, io bound operations

slate swan
shrewd apex
slate swan
shrewd apex
#

asyncio.sleep is the alternative for async operations

formal basin
shrewd apex
#

yeah well look at other parts of your code

shrewd apex
#

on_message and received messages and working with them will not cause heartbeat errors at most ur bot will response to those messages will be a bit delayed

severe sonnet
#

Okay soo maybe i will need to re-invite my bot?```
ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Documents\GitHub\RP-Utilitites-Beta\cogs\ActionCog.py", line 42, in on_message
webhooks = await message.channel.webhooks()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\channel.py", line 564, in webhooks
data = await self._state.http.channel_webhooks(self.id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

slate swan
#

Ah yes, let's send a second time the exact same long traceback

violet anvil
#

@slate swan Let me check it also , thanks

slate swan
#

i suppose manage_webhooks

violet anvil
shrewd apex
#

edit the perms from roles

slate swan
austere prairie
shrewd apex
formal basin
#

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

shrewd apex
#

ok

violet anvil
#

Anyone form India 😁❓

shrewd apex
#

what would you do with that information

slate swan
#

🧐

formal basin
slate swan
#

ot moment

slate swan
formal basin
#

yes

cloud dawn
#

Btw when setting up the project pyright got an absolute stroke because the command is fully executed in the entry in the commit hook.

cloud dawn
shrewd apex
#

weird reges shouldnt block

cloud dawn
#

So for some reason pyright couldn't see all my deps

shrewd apex
#

are you opening files or smn here?

shrewd apex
#

this is in the pre-commit hook?

unkempt canyonBOT
#

.pre-commit-config.yaml line 54

entry: poetry run pyright .```
slate swan
#

i guess thats it

formal basin
shrewd apex
cloud dawn
# slate swan i guess thats it

I changed it to ```yml

  • repo: local
    hooks:
    • id: pyright
      name: pyright
      pass_filenames: false
      entry: poetry
      command: run pyright .
      language: python
      stages:
      • commit
#

Then it worked.

slate swan
#

entry should be poetry run though

cloud dawn
#

Or poetry shell

shrewd apex
#

poetry run should by default use the poetry env

formal basin
shrewd apex
#

if u ran poetry shell previously then pyright . alone would suffice

cloud dawn
#

It shouldn't be..

shrewd apex
#

i am still confused

#

too much cofusion here 😭

shrewd apex
violet anvil
#

Yoo. I leaned many things about python 😁😁

slate swan
shrewd apex
#

tbh i feel like set comparisons would be much faster than regexing every message

shrewd apex
cloud dawn
violet anvil
slate swan
formal basin
violet anvil
shrewd apex
violet anvil
#

Now going to solve some basic problem of python .

shrewd apex
#

atb

formal basin
# shrewd apex can u show the function that ur using once
for pattern in new_words_list:
        if re.search(pattern, sws, re.IGNORECASE) is not None or re.search(pattern, replaceDoubleCharacters(sws), re.IGNORECASE) is not None or re.search(pattern, replacespecialcharacters(sws), re.IGNORECASE) is not None or  re.search(pattern, replacespaces(sws), re.IGNORECASE) is not None:```
violet anvil
#

Any one give any question ❓😁

formal basin
shrewd apex
slate swan
violet anvil
shrewd apex
#

damn op ^^

shrewd apex
#

send me code for one of those functions btw

cloud dawn
shrewd apex
#

also why is not None for everything with or just use any()

violet anvil
formal basin
# shrewd apex send me code for one of those functions btw
def replaceDoubleCharacters(string):
    lastLetter, replacedString = "", ""
    for letter in string:
        if letter != lastLetter:
            replacedString += letter
        lastLetter = letter
    return replacedString


def replacespaces(s):
    s = replaceDoubleCharacters(unidecode(s))
    return s
    
    

def replacespecialcharacters(s):
  special_characters = r"[.\/,'|*=\-_`!<>+$%^?!!1234567890@ ]"
  string_without_special_characters = re.sub(special_characters, "", s)
  string_without_special_characters= replaceDoubleCharacters(string_without_special_characters) or unidecode(s)
  return string_without_special_characters
  
rugged shadow
naive briar
#

No one does 🙀

rugged shadow
#

thank you for sharing this information sir

violet anvil
shrewd apex
#

whats unidecode

#

is that a standard lib?

rugged shadow
formal basin
violet anvil
rugged shadow
#

?

violet anvil
formal basin
rugged shadow
#

what code?

#

i didnt write any code in this channel

shrewd apex
#

like this regex code

#

then its likely some other part of the code blocking

violet anvil
shrewd apex
#

are u running some blocking tasks during startup

austere prairie
rugged shadow
#

that's just a for loop

#

they were talking about calling the function, not defining one

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.

violet anvil
#

Ok now i understood 😁

austere prairie
violet anvil
rugged shadow
#

npnp

violet anvil
rugged shadow
#

a little bit

violet anvil
#

By seeing you Id i ask 😂

rugged shadow
rugged shadow
shrewd apex
#

python >>>

rugged shadow
#

rust >>>>>

formal basin
violet anvil
shrewd apex
#

r.exists(key3) whats r?

austere prairie
formal basin
shrewd apex
#

isnt redis sync by default

violet anvil
shrewd apex
#

its blocking i am 90% sure

#

!pypi aioredis

unkempt canyonBOT
shrewd apex
#

u prolly want this

violet anvil
#

It is an python library

shrewd apex
#

ok stop stating the obvious now 🗿

formal basin
shrewd apex
#

wdym how?

violet anvil
formal basin
shrewd apex
#

read its docs

formal basin
#

do I just install it?

shrewd apex
#

wait if ur using redis lib from pypi

#

then it seems to have an async module too

violet anvil
shrewd apex
formal basin
formal basin
violet anvil
shrewd apex
violet anvil
shrewd apex
buoyant quail
#

personal chatgpt

violet anvil
shrewd apex
#

and ur wrong

#

its the name of a website where python libraries are listed

violet anvil
buoyant quail
#

!pypi pypi

unkempt canyonBOT
slate swan
#

!pypi pip

unkempt canyonBOT
#

The PyPA recommended tool for installing Python packages.

shrewd apex
#

Python Package Index

visual island
shrewd apex
violet anvil
buoyant quail
#

but exists 😄

shrewd apex
#

sure

slate swan
#

!pypi

unkempt canyonBOT
#
Missing required argument

package

#
Command Help

!pypi <package>
Can also use: pack, package, pip

Provide information about a specific package from PyPI.

slate swan
#

should send link to website imo

formal basin
#

im confused

#

it cant be redis

formal basin
#

when i took the functions off it stopped blocking heartbeat

austere prairie
#

You can use "|".join for that

#

And maybe pre-generate the regex pattern too

formal basin
#

no the functions are doing it

austere prairie
#

That's because you're running the functions 900 times, for each word

formal basin
#

ohhh

austere prairie
#

You could also run them once outside of the loop entirely

#

But you may as well optimize the regex too

formal basin
austere prairie
#

Do it outside of the loop, or use a single regex for everything

severe sonnet
#

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

formal basin
formal basin
#

when putting out of the for loop

formal basin
austere prairie
potent mulch
#

where can i find the json docs?

slate swan
#

!d json

unkempt canyonBOT
#

Source code: Lib/json/__init__.py

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).

Warning

Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.

json exposes an API familiar to users of the standard library marshal and pickle modules.

Encoding basic Python object hierarchies:

potent mulch
potent mulch
#

so i can save/send/read json files with the bot

#

i've done it, but in js

slate swan
#

json works the same in each language

potent mulch
#

oh

#

well, uhm

slate swan
potent mulch
#

how it works and like, everything about it lol

wicked atlas
#

do you mean the discord API docs?

potent mulch
#

maybe yes, not sure about that

wicked atlas
potent mulch
#

i don't really need error messages code...

#

to be more specific
i'm trying to do a command that if sent, give you a list of things, everything wrote on a json file

slate swan
#

so you wanna know how to send a file?

#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

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

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

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

you pass file kwarg

potent mulch
potent mulch
#

and maybe write lol

slate swan
potent mulch
#

not understanding

buoyant quail
#

reading and writing is just a python thing. you do it as usual

buoyant quail
potent mulch
slate swan
#

!open

unkempt canyonBOT
#
Opening files

The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.

See also:
!tags with for information on context managers
!tags pathlib for an alternative way of opening files
!tags seek for information on changing your position in a file

The file parameter

This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.

An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.

See !tags relative-path for more information on relative paths.

The mode parameter

This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.

'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)

potent mulch
#

alr

south aurora
#

im looking for someone to make me code for a discord bot so all i have to do is input the token through a secret and add the hosting code

slate swan
south aurora
dusk dagger
buoyant quail
#

Here is your bot:

TOKEN = "PUT YOUR TOKEN HERE"
print("IMAGINE A DISCORD BOT RUNNING")
hasty coral
#

whats the function for deleting the command trigger once a command is executed?

slate swan
#

In the end

can someone pls kod for mi

buoyant quail
unkempt canyonBOT
#

remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) from the internal list of commands.

This could also be used as a way to remove aliases.

Changed in version 2.0: `name` parameter is now positional-only.
hasty coral
slate swan
#

ah ok

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
slate swan
#

!D discord.Interaction.message

unkempt canyonBOT
sick birch
buoyant quail
#

You need to drink i guess

dusk dagger
# slate swan !D discord.Interaction.message

Don’t use this to delete the message, calling raw methods on the message incurs rate limits. Take a look at interaction.delete_original_response() which is free of rate limits.

buoyant quail
#

It's an api call too?

#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
buoyant quail
#

Do they have some different rate limits?

dusk dagger
#

Read the bottom part of that

slate swan
#

but we are not fetching message anyways

dusk dagger
#

interaction.message.delete() fetches the message

buoyant quail
#

interaction.message is not a fetch.
but it doesn't return a sent message

#

The actual method with getting message would be message = await interaction.original_response() + await message.delete()

hasty coral
dusk dagger
#

Or just use delete_original_response()

dusk dagger
hasty coral
#

its a prefix command not an interaction command so i cant can i?

@bot.command()
async def status(ctx):
    embed = discord.Embed(title='![BotOnline](https://cdn.discordapp.com/emojis/1126202487318253588.webp?size=128 "BotOnline") Verde Status Check', description=f"**Server Count** | {format(len(bot.guilds), ',')}\n**User Count** | {format(len(bot.users), ',')}\n**Latency** | {bot.latency*1000:.2f} ms\n**Report Time** | {formatted_datetime}", color=discord.Color.brand_green())
    await ctx.channel.purge(limit=1)
    await ctx.send(embed=embed)
slate swan
#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

sick birch
slate swan
hasty coral
buoyant quail
hasty coral
slate swan
buoyant quail
#

Any language you can imagine actually exists in discord

hasty coral
buoyant quail
#

there is even brainfuck for example

hasty coral
#

learn sum new everyday i suppose

slate swan
#
+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+.
#

?

#

cool

slate swan
#

hi

buoyant quail
#

actually.. idk how to color it better so..

slate swan
#
def drive(%User{age: age}) when age >= 16 do
  # Code that drives a car
end

drive(User.get("John Doe"))
buoyant quail
#

wtf

slate swan
#

interesting

meager rock
#
HAI 1.2
  I HAS A VAR_A ITZ 5
  I HAS A VAR_B ITZ 10
  
  VAR_A R SUM OF VAR_A AN VAR_B  BTW 15
  VAR_B R DIFF OF VAR_A AN VAR_B  BTW 5
  
  VAR_A R DIFF OF VAR_A AN VAR_B  BTW 10
  
  VISIBLE "VAR_A: " VAR_A
  VISIBLE "VAR_B: " VAR_B
KTHXBYE
#

( anyways, ot)

slate swan
#

lolcode lexer interesting

buoyant quail
#

1c
4d
abnf
ada

#

what these languages even are

#

i is a language

#

hmm, or not

#

it is in the files

#

but not with the code block

buoyant quail
#

it's actually the 1С language

#

lmao

slate swan
#
#ЗагрузитьИзФайла ext_module.txt // директива 7.7
#Если Клиент ИЛИ НаКлиенте Тогда // инструкции препроцессора
    &НаКлиентеНаСервереБезКонтекста // директивы компиляции
    Функция ТолстыйКлиентОбычноеПриложение(Знач Параметр1 = Неопределено, // комментарий
        Параметр2 = "", ПараметрN = 123.45, ПарамNN) Экспорт // еще комментарий
        Попытка
            Результат_Булевы_Значения = Новый Структура("П1, П2", Истина, Ложь, NULL, Неопределено);
            Перейти ~МеткаGOTO; // комментарий
            РезультатТаблицаДат = Новый ТаблицаЗначений;
            РезультатТаблицаДат.Колонки.Добавить("Колонка1", 
            Новый ОписаниеТипов("Дата", , ,
            Новый КвалификаторыДаты(ЧастиДаты.ДатаВремя));
            НС = РезультатТаблицаДат.Добавить(); НС["Колонка1"] = '20170101120000');
        Исключение
            ОписаниеОшибки = ОписаниеОшибки(); // встроенная функция
            Масс = Новый Массив; // встроенный тип
            Для Каждого Значение Из Масс Цикл
                Сообщить(Значение + Символы.ПС + "
                |продолжение строки"); // продолжение многострочной строки
buoyant quail
#

: )

slate swan
#

i guess its normal language when translated xd

buoyant quail
#
#LoadFromFile ext_module.txt
#If Client OR OnClient Then
    &OnClientOnServerWithoutContext
    function FatClientCommonApplication()
#

i am lazy for more

slate swan
#
Hello, World!
============
Author Name, <author@domain.foo>

you can write text http://example.com[with links], optionally
using an explicit link:http://example.com[link prefix].

* single quotes around a phrase place 'emphasis'
** alternatively, you can put underlines around a phrase to add _emphasis_
* astericks around a phrase make the text *bold*
* pluses around a phrase make it +monospaced+
* `smart' quotes using a leading backtick and trailing single quote
** use two of each for double ``smart'' quotes

- escape characters are supported
- you can escape a quote inside emphasized text like 'here\'s johnny!'

term:: definition
 another term:: another definition
``` this actually fire
#

ok we need to ask question about discord bots

buoyant quail
#

Use discord_slash and discord_components libraries

#

They are made specially for this

slate swan
#

oh okay thanks

#

but

#

can you give me code to copy paste???

buoyant quail
#

Check out this video, there is a github linked

slate swan
#

damn

hasty coral
#

Im trying to create a slots command but keep getting the same error.

Code:

@bot.tree.command(name='slots', description='Gamble on Slots')
@app_commands.describe(amount = 'amount')
async def slots(ctx:discord.Interaction, amount: int):
    with open('userBalances.json', 'r') as f:
        balances = json.load(f)
    user_id = str(ctx.user.id)
    user_balance = balances.get(user_id, 0)
    if user_balance >= amount:
        outcomes = ['✅','❌']
        slot1 = random.choice[outcomes]
        slot2 = random.choice[outcomes]
        slot3 = random.choice[outcomes]
        user_balance -= amount
        if slot1 == slot2 and slot2 == slot3:
            winning_amount = amount*2
            embed = discord.Embed(title='Slot Machine', color=discord.Color.brand_green())
            embed.add_field(name='**Result**', value=f'{slot1} | {slot2} | {slot3}', inline=False)
            embed.add_field(name='You Win!', value=f'You bet {amount} Coins and won {winning_amount} Coins.', inline=False)
            await ctx.response.send_message(embed=embed)
            user_balance += winning_amount
            balances[user_id] = user_balance
            with open('userBalances.json', 'w') as f:
                json.dump(balances, f, indent=4)
        else:
            embed = discord.Embed(title='Slot Machine', color=discord.Color.brand_red())
            embed.add_field(name='**Result**', value=f'{slot1} | {slot2} | {slot3}', inline=False)
            embed.add_field(name='You Lost!', value=f'You bet {amount} Coins and lost them.', inline=False)
            await ctx.response.send_message(embed=embed)
    else:
        await ctx.response.send_message(f'{ctx.user.mention} you do not have enough Coins in your balance to make this bet.\nUse /balance to view how many Coins you have.')

Error:

  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\jackf\Documents\Verde Discord Bot\main.py", line 868, in slots
    slot1 = random.choice[outcomes]
TypeError: 'method' object is not subscriptable```
slate swan
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError).
slate swan
hasty coral
#

the issue im having is that a command on one of my other bots uses the same code yet this one doesn't work

slate swan
#

its impossible it worked since the syntax is incorrect

slate swan
potent mulch
#

How can i edit a message that have been sent in async def test(ctx): from a class?

#
@bot.command()
async def test(ctx):
    view = DropdownView()

    requesting_message = await ctx.send(embed=embed, view=view)
    await asyncio.sleep(1)
    await requesting_message.edit(embed=embed2)

class Dropdown(discord.ui.Select):
    def __init__(self):
        options = [
            discord.SelectOption(label="Database-Staff", description="Database dello Staff"),
            discord.SelectOption(label="Database-Car", description="Database Auto"),
        ]
        super().__init__(placeholder="Seleziona un Database", min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "Database-Staff":
            await interaction.response.send_message(f"{self.values[0]}")
        elif self.values[0] == "Database-Car":
            await interaction.response.send_message(embed=discord.Embed.from_dict(embed_dict), ephemeral=False)

Just to make sure you understand, i have this and after the Dropdown is selected, the message have to be changed. ;-;

potent mulch
#

nvm

ebon island
#

Hey there! I know Discord.py was making a return, previously I was using Disnake, as well as many others. My question: what is the current most feature rich / best supported / best implementation of Discord in Python?

mighty pilot
#

I think it's personal choice tbh. Seems like disnake is more user friendly on the dev side from what I've heard, but I've never used it just discord.py

potent mulch
#

why this keep happen?

#

i get no error in the console tho

potent mulch
mighty pilot
potent mulch
mighty pilot
#

If you have no interaction.response then it'll say failed every time.

potent mulch
#

but what if i don't really want to send a message?

mighty pilot
#

You could make it send an ephemeral message if you don't want something everyone can see

potent mulch
#

even if it's ephemeral=False

potent mulch
mighty pilot
#

Idkchu haven't tried to get around that myself. I like to have a positive indication something is happening

potent mulch
#

wait i'll search something

#

i'll try and say if it works

mighty pilot
potent mulch
#

can't, it's a button to change page

#

it works with the await interaction.response.defer()

mighty pilot
#

Ok

potent mulch
#

just have to do some changes and it should be fine, ty

final iron
mighty pilot
#

I wasn't sure if you could open endedly defer

#

Now I know

toxic moat
#

I am trying to create a custom embed command that people can use with adminastrator roles. I am very confused while doing this and I would like help if anyone can help me.

What I'm trying to do with the custom embed:
Allow the user to add a title, descriptoin, image, footer AND a button

So if anyone knows how to do this please reply or mention me.

final iron
#

With prefixed commands, slash commands or modals?

#

Or dropdowns

#

Do you want to do it in multiple messages or just one?

toxic moat
toxic moat
final iron
#

This sounds relatively simple

#

What are you having trouble with?

toxic moat
toxic moat
final iron
#

Well you would just have them as args in your slash command

#

Set certain ones as optional, others as required

toxic moat
#

and in the slash command u can set the custom embed to send to a specific channel and everything

final iron
#

Oh, so it's not a dynamic generator? An administrator sets the format, and that get saved?

#

Do you have any code so far?

toxic moat
sick birch
toxic moat
slate swan
#
async def join(interaction: Interaction):
    """Join the voice channel the user is in"""
    if interaction.user.voice:
        channel = interaction.user.voice.channel
        await channel.connect()
    else:
        await interaction.response.send_message("not in a voice channel")```
why does this always provide '``not in a voice channel``' even when im in one?
final iron
final iron
slate swan
#

yesh

#
intents.typing = True
intents.presences = True
client = discord.Client(intents=intents)```
final iron
#

@toxic moat Do you have any code so far for your command?

toxic moat
tall temple
#
if os.path.exists("config/payment.png") :
  file = discord.File("config/payment.png", filename = "payment.png")
  embed.set_image(url = "attachment://config/payment.png")
await ctx.respond(file = file, embed = embed)
slate swan
tall temple
#

can someonehelp me pls ?

final iron
slate swan
#

it has admin perms

final iron
#

And you're running the command in a guild?

slate swan
#

yes

#

it just doesnt detect im in a vc

final iron
#

I'm aware

#

Voice is printed as None, correct?

slate swan
#

yes

#

we ignore everything here

#

besides what matters

golden portal
toxic moat
tall temple
#

the file is didn't appear when i executed the command (rn)

golden portal
#

please read on what i said

tall temple
#

@golden portal could you give me a syntax pls ?

golden portal
#

the error however i dont know since i dont use that fork

tall temple
#

oh ok my bad

#

thanks

golden portal
#

yea i dont really use that lib

final iron
tall temple
#

thanks for help

#

@final iron could you help with that case 🙂 ?

final iron
#

Aside from the bot not being able to see the channel, (it could have user specific permissions) I don’t know why it wouldn’t be able to get your voice state

vocal laurel
#

is that a d.py fork or smth?

slate swan
final iron
#

Prob

vocal laurel
#

or is that actaully smth

golden portal
vocal laurel
final iron
slate swan
#

it's

#

everyone can see, bot has admin perms

final iron
#

Humour me

slate swan
#

i've been tryna figure this out on like 5 different severs, tons of different VC's

final iron
toxic moat
#

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    content = message.content.lower()

    author_highest_role = message.author.top_role
    bot_highest_role = message.guild.me.top_role

    if bot_highest_role < author_highest_role:
        if any(word in content for word in FILTERED_WORDS):
            await message.delete()
            await message.channel.send(f"{message.author.mention}, that's not allowed!")```

**Why doesn't this work I get no error in the terminal.**
toxic moat
# upbeat gust what happens?

litteraly nothing happens the bot does not delete the message, and does not say anything after they sent one of the filter words

upbeat gust
#

Do you have logging? do you have the message content intent?

toxic moat
upbeat gust
upbeat gust
#

then you should have logging-

#

are you sure you dont? nothing in the terminal

toxic moat
final iron
toxic moat
final iron
#

Show your dev portal

#

!d discord.Member.top_role

unkempt canyonBOT
#

property top_role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
toxic moat
final iron
#

Show it

#

Show it being enabled

slate swan
#

mb for late i took a shower

final iron
#

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

slate swan
final iron
#

How many lines?

slate swan
#

400-500ish

toxic moat
toxic moat
slate swan
final iron
# toxic moat

Is your role higher in the hierarchy than your bots?

slate swan
#

but it's 400-500 lines and i don't think it's very convenient to just paste 400-500 lines and say "yeah read the whole thing"

final iron
#

People have done worse

#

Just send it, I want to check something

slate swan
#

okay

final iron
#

I honestly find your situation pretty strange

slate swan
#

enjoy my entire bot client lmao

#

has a key system and config file save

final iron
#

Humor me, see if it works if you set your intents to all

toxic moat
slate swan
#

by what?

toxic moat
#

iplookup

slate swan
#

i dont believe it is?

#

its a public API

toxic moat
#

oh okay

slate swan
final iron
#

Might be some weird slash command interactions

#

What if you get() the user object and see if it says it's connected?

#

Just as a temporary measure

slate swan
#

um what

#

it doesn't detect that i'm in a VC at all, if i saw i was connected but couldn't transfer it to connection it would raise a different error

final iron
#

what

#

What does that have to do with what I said

#

get() the discord.Member object and see if it says it's in a voice channel

final iron
toxic moat
final iron
#

Bot is higher than your bot?

#

You mean the bot is higher than your alt?

toxic moat
final iron
#

!e

print(1 < 2)
unkempt canyonBOT
#

@final iron :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
vocal laurel
#

wha-

final iron
#

Example for him

final iron
# toxic moat yep

Right now you're checking if the authors highest role is higher than the bots

#

You just told me that's not true

final iron
#

...

#

Just flip the symbol...

#

Why do you have that there in the first place, what are you trying to acomplish with it

tranquil pasture
#

I want to know the internal working of bot.load_extension?

quick brook
unkempt canyonBOT
#

discord/ext/commands/bot.py line 962

async def load_extension(self, name: str, *, package: Optional[str] = None) -> None:```
quick brook
#

feel free to read the source code if you want to

tranquil pasture
quick brook
tranquil pasture
#

btw is it possible to implement this in another python project?

quick brook
tranquil pasture
tranquil pasture
quick brook
quick brook
obsidian fable
#

is there any way to hide a slash command for everyone except for specified User IDs or check if user is owner

toxic moat
#
from discord.ext import commands, tasks
import asyncio

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

# Initialize bot with command prefix '!'
bot = commands.Bot(command_prefix='!', intents=intents)

BOT_PREFIX = '!'

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} - {bot.user.id}')
    print('------')
    watching_activity = discord.Activity(type=discord.ActivityType.watching, name="over AutoShop")
    await bot.change_presence(activity=watching_activity)

@bot.command()
async def purchase(ctx):
    # Replace these placeholders with your actual PayPal and crypto wallet addresses
    paypal_address = "**[PayPal](https://www.paypal.me/erfanproguy2)**"
    bitcoin_wallet = '**bc1q5cf7v6lr7yrtdferlqq07hqww7wqw8dfwp5a66**'
    litecoin_wallet = '**Laf9AR7LdtrpkrTgFkx5RVci65ngxViTqa**'
    ethereum_wallet = '**0x3f74a98bA3468e25F9cFc02852BF7883B4D707e9**'

    embed = discord.Embed(title="Purchase Information", description="Here are the following purchase options:", color=0x00ff00)
    embed.add_field(name="![paypal](https://cdn.discordapp.com/emojis/1145503563934609529.webp?size=128 "paypal") Paypal", value=paypal_address, inline=False)
    embed.add_field(name="![btc](https://cdn.discordapp.com/emojis/1145502468957032598.webp?size=128 "btc") Bitcoin Wallet", value=bitcoin_wallet, inline=False)
    embed.add_field(name="![ltc](https://cdn.discordapp.com/emojis/1145502474879381586.webp?size=128 "ltc") Litecoin Wallet", value=litecoin_wallet, inline=False)
    embed.add_field(name="![eth](https://cdn.discordapp.com/emojis/1145502472882892920.webp?size=128 "eth") Ethereum Wallet", value=ethereum_wallet, inline=False)
    await ctx.send(embed=embed)

@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        # Respond with the bot's prefix
        await message.channel.send(f"My prefix is `{BOT_PREFIX}`")

bot.run('')```

**Why is none of this working..** # no errors btw
#

@final iron

wispy pasture
#

sooo.... idk why its marking it, but it is... and i dont see any error...

class CreateSelect(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.select(
        custom_id="ticketopen",
        options=[
            discord.SelectOption(label="What is Sampler", emoji="✨"),
            discord.SelectOption(label="Guide to AI Models", emoji="📚"),
        ],
    )```
#

it says this

toxic moat
#

doesnt help at all

naive briar
#

I hope it's not in the if-statement

toxic moat
# naive briar Where did you put it?
async def on_message(message):
    if bot.user.mentioned_in(message):
        # Respond with the bot's prefix
        await message.channel.send(f"My prefix is `{BOT_PREFIX}`")
        await bot.process_commands(message)```
naive briar
#

Move it out of the if-statement

toxic moat
toxic moat
lethal drift
#

Is it possible to receive a slash command message ID before a message is sent? I'm trying to make sure the purge command I have doesn't delete the original invoking of the command before it responds.

it goes in this order: Invoke -> Purges Messages -> Says how many deleted msgs