#discord-bots

1 messages · Page 27 of 1

onyx aspen
slate swan
#

👁️ 👁️ 👁️

#

statically typed😳 😏

#

pretty basic atm

silk fulcrum
onyx aspen
#

I don't really understand any of it tbh

#

it just goes over my head

slate swan
silk fulcrum
onyx aspen
#

ik but I dont

slate swan
silk fulcrum
#

then what do you want?

slate swan
onyx aspen
#

that's why I asked here if someone would be able to help explain it?

slate swan
#

pigeon, how experienced are you with python?

slate swan
onyx aspen
silk fulcrum
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.

onyx aspen
#

hm?

slate swan
silk fulcrum
#

and pushed

slate swan
#

yeah, sadly

slate swan
slim grotto
#

How can I cancel a command from executing through on_command?

@bot.event
async def on_command(ctx):
  if ctx.invoked_with == ...: # Meets some condition
    # cancel command from executing
silk fulcrum
#

wtf im scrolling page up but it returns me back to where i was

slate swan
#

ngl, the events are inspired by hikari
except for the single time listeners

slate swan
slate swan
onyx aspen
silk fulcrum
slate swan
slate swan
onyx aspen
silk fulcrum
onyx aspen
#

all I need to know is this one question and I'll be on my way

scarlet aurora
silk fulcrum
onyx aspen
#

mhm

#

I already have a bot

#

I'm just confused on how to integrate the slash commands

austere vale
#
PreviousButton = nextcord.ui.Button(emoji:id=1006237375938179142)

could someone help me format buttons correctly? im just trying to set the button to the ⬅️emoji

sick birch
scarlet aurora
slate swan
#

why doesn't my bot have a description even though i entered one?

austere vale
#

does anyone know what this error means?

sick birch
austere vale
scarlet aurora
sick birch
#

One good thing about Arch is I don't have to worry about updating my Python, it's always bleeding edge 😄

paper sluice
#

you use arch no gui?

scarlet aurora
sick birch
paper sluice
#

ohh, nice

slate swan
#

i use windows vista

slate swan
#

updating python would be the best choice

#

yeah iirc __class_getitem__ was impl in 3.9

left idol
#

im in pycord and i can't seem to have my OptionChoice show up at all. im trying a test command but it still isn't showing up,

classes_list = [
    OptionChoice(name = 'Tank', Value = 'Tank'),
    OptionChoice(name = 'Assassin', Value = 'Assassin'),
    OptionChoice(name = 'Fighter', Value = 'Fighter')
]
#
async def poopingtest(ctx, classes: Option(str, 'Class choice', choices = classes_list)):
scarlet aurora
#
    @commands.command()
    async def addname(self, ctx, name):
        e = conn.cursor()
        x = ctx.author.id
        y = name

        e.execute('''INSERT INTO names
        (user, name)
        VALUES (?, ?);''',
        (x, y))
        conn.commit()

        await ctx.send("Registered")

    @commands.command()
    async def deletename(self, ctx, name):
        e = conn.cursor()
        x = ctx.author.id
        y = name

        e.execute("""DELETE FROM names WHERE user = ? and name = ?;""", (x, y))

        conn.commit()

        await ctx.send(f"{name} successfully deleted")

    @commands.command()
    async def name(self, ctx, name: discord.Member):
        e = conn.cursor()
        id = name.id

        e.execute("""SELECT name FROM names WHERE user= ?;""", (id,))

        await ctx.send(e.fetchall())

    @commands.command()
    async def namelist(self, ctx):
        e = conn.cursor()

        e.execute("""SELECT name FROM names""")

        await ctx.send(e.fetchall())```Hi I'm having a problem with my sqlite3 database, I made it so that I can store contents inside of the database via a discord bot / commands, and it stores them perfectly and retains them, but every day the table contents reset apart from the ones MYSELF has set
cerulean solstice
#
@bot.command(pass_context=True)
async def meme(ctx):
    embed = discord.Embed(title="", description="")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await ctx.send(embed=embed)

the code isnt working
like it isnt sending out the meme
this error comes:

#
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 16, in meme
    async with aiohttp.ClientSession() as cs:
NameError: name 'aiohttp' is not defined

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

Traceback (most recent call last):
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'aiohttp' is not defined
#

how do i define it?

paper sluice
#

you need to install the library then import it

#

!pip aiohttp

cerulean solstice
paper sluice
slate swan
#

!pypi aiohttp

unkempt canyonBOT
slate swan
#

you possess a skill issue

#

kinda funny how edited is shown

cerulean solstice
#

does not work so what should i do?

paper sluice
paper sluice
cerulean solstice
slate swan
cerulean solstice
#

how do i install it

unkempt canyonBOT
slate swan
#

💀

#

took an hour😭

paper sluice
slate swan
#

how did it got delayed so hard😭

paper sluice
cerulean solstice
#

ohk wasnt loading for me

pliant gulch
#

Why do you need to install aiohttp

#

It's a dependency, just import it

#

If you didn't have it installed and actually did import you'd get ModuleNotFoundError but your getting a NameError here meaning you never even tried importing

scarlet aurora
left idol
#

did i mess up on the format for this? i'm not even getting any options showing up when i type the command
``async def poopingtest(ctx, class_choice: option(str, 'Class choice', choices = classes_list)):`

#

also tried with capital Option

limber bison
#

2,0 is shit , why i dont able to reload tha same name cog with extra commands

#

why

slate swan
#

Tried earlier got this message for some reason :/
Do note: I'm using Visual Studio Code.

glad cradle
slate swan
#

uhhhhhhhhhhhh e

#

!dashmpip

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

slate swan
royal meteor
#

How to do embed pagination?

vocal snow
slate swan
#

I installed git

vocal snow
#

and did you add it to PATH?

#

run git --version and see

silk fulcrum
vocal snow
mossy jacinth
#

how can i make a mute command like dyno? That it gives the user a timeout?

slate swan
silk fulcrum
#

ohkay

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
silk fulcrum
#

im too late(

mossy jacinth
silk fulcrum
#

I was thinking of it but I decided to check in docs if that is time_out or timeout

limber bison
#

client = commands.Bot(command_prefix=commands.when_mentioned or (config["prefix"]), intents=intents ) why my prefix dont working?

slate swan
slate swan
limber bison
#

why this or ?

slate swan
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
slate swan
#

because that's the function, or in python is different

mossy jacinth
#

how can i make it that its automatically minutes? and not 0:00:00?

tame raft
#

does import discord still exist?

slate swan
#

???

white aurora
#

yes

grim oar
grim oar
tame raft
grim oar
#

pip install discord.py

tame raft
#

oh

#

i forgot

#

ty

grim oar
#

👍

cold sonnet
#

please install 2.0

tame raft
#

@grim oar

cold sonnet
#

python -m pip install git+https://github.com/Rapptz/discord.py

grim oar
tame raft
#

wdym

grim oar
#

The command

tame raft
#

terminal

#

vsc terminal

cold sonnet
#

pip isn't on your path, you'd have to search the pip folder in your python folder and add it to path

#

or use python -m pip

#

python or py is most probably on your path

tame raft
#

how do i add it to the path

mystic star
#

you probably need to use a virtual env

cold sonnet
#

you don't even have python...

tame raft
cold sonnet
#

ctrl + shift + p
in vsc, then "select python interpreter"

#

what does it show

tame raft
#

lemme check

tame raft
cold sonnet
#

what

#

ok then

tame raft
cold sonnet
#

do as the terminal said and run
python

tame raft
#

i dont understand

slate swan
#

How can I add choice to slash command as user id?

slate swan
#

looks like pycharm to me

swift pumice
#

oh ok

#

thanks

silk fulcrum
slate swan
#

yeah

vale wing
#

@tame raft just reinstall python but put the Add Python to PATH checkmark when installing

vale wing
#

👍

mossy jacinth
#

why can I still type? I dont have any perms or other roles

vale wing
#

His name is very sus doe

vale wing
#

Probably like everyone role has explicit send message perm set to true

#

Also look at the underlines and pay attention to the recommendations, they'll make your code better

#

Pycharm is so great for improving code style imho

slate swan
#

😍

#

😳

royal meteor
#

I am making a ban command for my bot, and I realised when I manually try to ban somebody, I can give a reason and a Delete Message History option. How can I implement the same feature so the bot specifies it?

slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
slate swan
#

reason is the reason for ban

#

@royal meteor

royal meteor
smoky cedar
#

How do people adequately test discord bots (automation wise) without the ability to allow a bot to create a server?

#

Just having a test server and cleaning up data each time?

slate swan
#

What do ya mean?

smoky cedar
#

I guess I could unit test the methods without issuing a slash command but then is there a way to mock an interaction object? Or would you just have a bot issue slash command to itself?

night crater
#

is this REST or WS based?

slate swan
#

@night crater is your pfp ashley rosemary?

night crater
slate swan
#

I'm pretty sure it is 😳

night crater
#

And how would you know that 👁️

slate swan
sudden crypt
#

how can i get the ids of which user joins the server

zealous jay
#

So I have a list, how could I make it so I have like 4 items per page on an embed? I have never used embed pages

limber bison
#

2.0 api link

#

🤔

#
if user is None:
            user = ctx.author
        try:
            bal = await economy.find_one({"id": user.id})
            if bal is None:
                await self.open_account(user.id)
                bal = await economy.find_one({"id": user.id})
            embed = discord.Embed(
                timestamp=ctx.message.created_at,
                title=f"{user}'s Balance",
                color= random.choice(colors),
            )
            embed.add_field(
                name="PAOD's",
                value=f"${bal['PAODs']}",
            )
            embed.set_footer(
                text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
            )
            embed.set_thumbnail(url=user.avatar_url)
            await ctx.send(embed=embed)```
#

py 2.0 // whats wrong ??

slate swan
unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

If I remember correctly you cannot have a try without an except block

#
try:
  # do something
except some_error:
   # error, do something
#

is anyone error raising? @limber bison

limber bison
#

hehehe

slate swan
#

Well what's the error?

limber bison
#
try:
            bal = await economy.find_one({"id": user.id})
            if bal is None:
                await self.open_account(user.id)
                bal = await economy.find_one({"id": user.id})
            embed = discord.Embed(
                timestamp=ctx.message.created_at,
                title=f"{user}'s Balance",
                color= random.choice(colors),
            )
            embed.add_field(
                name="PAOD's",
                value=f"${bal['PAODs']}",
            )
            embed.set_footer(
                text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
            )
            embed.set_thumbnail(url=user.avatar_url)
            await ctx.send(embed=embed)
        except Exception:
            await ctx.send('An error occured')```
slate swan
#

What's the error

limber bison
#

just showing except output

#

avatar_url ??

#

in 2.0 ??

#

something ?

slate swan
#

raise the exception

gusty shard
#

my bot has ```<p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>

#

did my bot baned from

#

discord..

slate swan
#

are you using replit

#

you're ratelimited

gusty shard
#

oh

#

that makes more sense

#

how can i prevent it?

slate swan
#

iirc replit uses shared IP's so it could've been some other person spamming the api

sick birch
gusty shard
#

i bought yearly plan

#

damn facepalm

gusty shard
#

or is it forbidden

zealous jay
slate swan
#

@gusty shard read this

gusty shard
#

thanks

slate swan
slate swan
#

cap

slate swan
#

capp

limber bison
#

discord.ext.commands.errors.ConversionError: (<class 'commands.pvc.pvc.DurationConverter'>, TypeError("new() missing 3 required positional arguments: 'name', 'bases', and 'namespace'"))

#
class DurationConverter(commands.Converter):
    async def convert(self ,  ctx , argument):
        amount = argument[:-1]
        unit = argument[-1]

        if amount.isdigit() and unit in [ 'm' , 'h']:
            return (int(amount),unit)

        raise commands.BadArgument(message='Not a vaild duration')    
    ```

is this ok in py2.0 ?
smoky cedar
#

Can you safely ping in ephemeral?

#

without affecting other users

zealous jay
#

Like a everyone?

smoky cedar
zealous jay
#

hmm I would say yes but I have not tested it so

sick birch
frail mesa
#

Hello, anyone that could offer advice?

I have a Discord bot that was made a very long time ago. I know the password as I use the same handful for everything, but I cannot for the life of me remember what email I used. Is there any way at all to find out what this is, or is my only option remaking the bot?

I do still have access to all the code, as it is hosted on Repl.it

sick birch
#

The discord bot should be tied to your account, should it not?

#

Can you log into your account on the development portal?

frail mesa
#

It is tied to a unique account made for the bot, not my account

sick birch
#

Ah okay. If you forgot your email I don't think there's a way to reset it, you could try contacting support

frail mesa
#

gotcha, this is what i figured. I suppose it wont be too much of a hassle to just copy/paste the code into a new bot, just annoying

#

or actually, if I make a new bot, all I would have to do is change the token, yea?

slate swan
#

Does anybody know how to setup a keyauth system with a bot is it easy?

#

also hi robin idk if you remember me

smoky cedar
#

Can you enable searching / typing in the placeholder part of a discord select field ?

smoky cedar
frail mesa
#

Ok so I'm just stupid, it was connected to my account lol, thats why i couldnt find the email

#

So it seems my bot has been temporarily banned because of rate limit. tried resetting the token to make sure it wasnt just an error, but yup, same errors

#

How do I go about fixing this? I'm not even sure how we could be exceeding rate limits, the bot has nothing but text commands

frail mesa
limber bison
#

await client.wait_for('message', check=check , timeout = 10) ??

#

is this ok ? error !!!

sick birch
limber bison
# sick birch What's the error?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

#

😳

#

@sick birch sir ?

cold sonnet
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cold sonnet
#

docs don't say anything

zealous jay
#

Is there a way to have an empty embed title? In this image I tried using \u200b that's supposed to be an empty character but It still renders that empty space

slate swan
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
zealous jay
#

oh

#

I forgot

slate swan
#

It's okay

limber bison
#

1 question

#

how can i remove a member from channel permission list

#

set_permissions set the pems but how to remove ??

smoky cedar
#

Could discord ever end up having guild ids or role ids over 19 integers?

#

No right? That's the max a database cold hold w a BIGINT?

sick birch
limber bison
#

can i reload bot vai commands

#

?

smoky cedar
#

How to add a role if they don't already have, and remove it otherwise? (IE a toggle)

#

Is there a clean / abstract way without doing checks on the user? In discord py

lone lichen
#

If they have role:
remove it
else:
give it

pale turtle
mossy jacinth
#

Hey! My mute command should setup a muted role with that the user cant write messages anymore and it should setup the channels but it doesnt and i can still type with my alt account, i have no permissions, the bot has permissions to everything

mental hollow
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

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

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

mental hollow
#

It’s only my help command that doesn’t work, all other prefixed commands are functional.

sick birch
#

Also looks like your help command is indented inside of the Help constructor

mental hollow
sick birch
#

Right, the issue is because your command is indented inside the constructor, so discord.py never picks it up

mental hollow
#

All cog commands are supposed to be indented into the cog class, no?

sick birch
#

Commands within cogs should look like so:

class MyCog(commands.Cog):
  def __init__(self, ...) -> None:
    ...

  @commands.command()
  async def my_command(self, ctx: commands.Context, ...) -> None:
    ...

not like this:

class MyCog(commands.Cog):
  def __init__(self, ...) -> None:
    ...

    @commands.command()
    async def my_command(self, ctx: commands.Context, ...) -> None:
      ...

^ which is what yours looks like

slate swan
#

for some reason the system thinks "import discord" isnt valid. (it was fine earlier)

sick birch
#

Type out exit(), then go about it as usual

slate swan
#

thx

smoky cedar
#

I have a bot with a select field that needs to go over 25 options. Can anyone send me a good guide of a decent solution maybe involving paging and buttons?

sick birch
radiant wing
#

How do I check for HTTP exception 429 specifically with try, except?

smoky cedar
#

Including buttons to page right?

sick birch
#

Ah, you've got more than 25 options?

smoky cedar
#

Yes hehe

sick birch
#

Hm. Might be better to just have a user input a number to select something, instead of a full on select/button pagination thing

mental hollow
mossy jacinth
smoky cedar
#

Basically, the bot allows server members to follow artists on spotify. Then it pings new releases to those who are assigned to the role it created. People can self-assign roles for the server's followed artists through the select menu at the moment

sick birch
#

So say you had a select with options 1-5, user presses the "next" button, edit the message with the same view, but options 6-10, etc

smoky cedar
sick birch
#

Yeah, you'd handle that inside of the button press callback

smoky cedar
#

Any idea what's going on here?

#

Including that line makes offset an unresolved variable

novel kelp
#

Any idea about putty ?

#

Like if want to edit something on awe I need to reupload right ?

fading marlin
smoky cedar
#

Like if I do this

offset = 25

async def page_select_forward(ctx: discord.Interaction):
  if offset == 25:
    view.add_item(prev_button)
    select.options = select_options[offset:offset+25]
    offset += 25
    ctx.response.defer()
#

Basically, trying to add 25 to offset is causing that error

#

otherwise, no error

fading marlin
#

ah, yes, offset is in your global scope, and you're trying to change the value of a global scope variable in a local scope variable. You can't do that. You have to make offset global inside your local scope.
You can still access global variables inside a local scope, hence why everything was alright until you added the offset += 25 bit

sick birch
#

If it's inside of a view or button subclass (which I suspect it is), you can bind it to self and access and write to it

mental hollow
#

Error:

Ignoring exception in view <HelpView timeout=180.0 children=1> for item <Select placeholder='Please select a category:' min_values=1 max_values=1 options=[<SelectOption label='Owner' value='Own' description='Select to view our Owner commands.' emoji=<PartialEmoji animated=False name='CL_AzielOwner' id=1000907171959161023> default=False>, <SelectOption label='Moderation' value='Mod' description='Select to view our Moderation commands.' emoji=<PartialEmoji animated=False name='CL_AzielMod' id=1000909301927395358> default=False>, <SelectOption label='Information' value='info' description='Select to see our infomational commands.' emoji=<PartialEmoji animated=False name='CL_Book' id=1000145556204691536> default=False>, <SelectOption label='Fun' value='Fun' description='Select to view our Fun commands.' emoji=<PartialEmoji animated=False name='CL_AzielGames' id=1000908640263344178> default=False>] disabled=False>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/help.py", line 44, in select_callback
    owner_cog = self.get_cog(name='Owner')
AttributeError: 'HelpView' object has no attribute 'get_cog'

Code: https://mystb.in/CommunistPrecedingVirtually.python

blazing beacon
#

how do i get a webhook with a specific name without having to iterate through all the channel webhooks

#

from mysql import connecter

#

idk

#

oh

slate swan
#

Did you install the package?

quaint epoch
#

to heck with pylance

#

it doesn't work half the time

#

continue anyway

#

i dunno

#

in pycharm you would just recheck for all errors and scan all packages again

#

no clue abt vsc

sick birch
#

Using and setting up a venv fixes up 99% of module importing errors

quaint epoch
#

do python -m venv .venv to make a .venv folder for your virtual environment

deep osprey
#

How to check how many servers the bot is running on every 5 minutes?

sick birch
#

Make sure you've got a MySQL server running on that machine and port, port forward if you have to. Configure your firewalls to let any packets in, make sure your username/password and any other authentication is correct

sick birch
#

Better suited towards #databases. I myself have never worked with mysql

south tundra
#

sorry im new to python but anyone knows why im not being responded to?


import random

import discord

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

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

    if message.content == "!randomnumber":
        await message.channel.send(message.author.display_name + " your random number is \n" + str(random.randint(1, 500)))

client.run("-_-")
deep osprey
#

How to check how many servers the bot is running on every 5 minutes?

heavy folio
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

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

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

south tundra
#

ohhhhhh

#

ty

deep osprey
sick birch
unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
deep osprey
# sick birch !d discord.ext.tasks.Loop
@tasks.loop(seconds = 5)
async def myLoop():
  
    numofservers = len(bot.guilds)
    activity = discord.Game(name=f'Watching {numofservers} servers', type=1)
    await bot.change_presence(status=discord.Status.online, activity=activity)

myLoop.start()``` is this code correct?
slender oriole
#

can anyone help me make a disscord bot plz ?

south tundra
#

yeah it doesn't work


import random

import discord

from discord import Intents
from discord.ext import commands

intents = Intents.default()

intents.members = True

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_message(message):
    if message.author != client.user:
        if 'randomnumber' == message.content:
            embed=discord.Embed(title="Random Number!", description=message.author.display_name + ", your random number is " + str(random.randint(0,1000)), color=0x8bc34a)
            await message.channel.send(embed=embed)
    await client.process_commands(message)

client.run("")
deep osprey
south tundra
#

looks good to me

#

iirc

deep osprey
#
    await self.coro(*args, **kwargs)
  File "main.py", line 184, in myLoop
    await bot.change_presence(status=discord.Status.online, activity=activity)
  File "/home/runner/EskusemeBot/venv/lib/python3.8/site-packages/discord/client.py", line 1062, in change_presence
    await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'``` got this error @sick birch
sick birch
sick birch
# deep osprey ```d/ext/tasks/__init__.py", line 101, in _loop await self.coro(*args, **kwa...

Might want to want until the bot is ready, see this example straight from the docs:

from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()
south tundra
sick birch
#

Right

south tundra
#

still doesn't work :/

magic ore
#

you don't pass the intents to the bot constructor

#

bot = Bot(..., intents=intents)

south tundra
#

ohhh

#

wait what?

#

import random

import discord

from discord import Intents
from discord.ext import commands

intents = Intents.default()

intents.members = True
intents.message_content = True

client = commands.Bot(intents.message_content = True, intents.members = True,command_prefix='!')

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_message(message):
    if message.author != client.user:
        if 'randomnumber' == message.content:
            embed=discord.Embed(title="Random Number!", description=message.author.display_name + ", your random number is " + str(random.randint(0,1000)), color=0x8bc34a)
            await message.channel.send(embed=embed)
    await client.process_commands(message)

client.run("")
mossy jacinth
#

How can i make it so it only sends the message once only? Either when member is None or; when time is None

south tundra
#

liike this?

magic ore
#

no, exactly how i showed; intents=intents, not intents.members=True

deep osprey
magic ore
#

(the latter is invalid syntax)

south tundra
#
intents.members = intents
intents.message_content = intents
```?
#

im sorry im dumb

sick birch
#

You're instantiating a class, changing properties/flags, whatever you want to call it, then passing the same class into the bot's constructor

south tundra
#

this should be it then right?

#
intents = Intents.default()

intents.members = True
intents.message_content = True

client = commands.Bot(command_prefix='!' + intents)
sick birch
#

!resources I think learning python itself can only help you, because right now it seems more of a hindrance. I don't mean to turn you away, but put discord bots on hold for a little bit as they're complex and require a good bit of Python knowledge

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.

south tundra
#

thank you for your help, ill try reading more up on it

deep osprey
smoky cedar
#

Can I have a prefix command redirect to a slash command, just by passing in the interaction object and manually calling the method?

sick birch
sick birch
sick birch
deep osprey
#
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
      numofservers = len(bot.guilds)
      activity = discord.Game(name=f'Watching {numofservers} servers',         type=1)
      await bot.change_presence(status=discord.Status.online, activity=activity)

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()``` should be this?
sick birch
#

That should cut it, make sure to change the names because "printer" is not an appropriate name for your method's usecase

deep osprey
slate swan
#

@deep osprey why did you define bot in your Cog file again, you need to use self.bot wherever you need to acess the bot inside a cog class

deep osprey
#

@slate swan @sick birch so any solution?

slate swan
#

show the full cog file

#

including the setup function

pulsar solstice
#

I am making a discord currency bot and want to store the data in a json file but i am getting a weird error

#

here is my code

#
import discord
from discord.ext import commands
import json

bot = commands.Bot(command_prefix=">", intent=discord.Intents.all())

@bot.event
async def on_ready():
    print("JOE TO GOOO...")


@bot.event
async def on_message(message):
    user_id=str(message.author.id)
    with open("jardb.json", "r") as f:
        jar=json.load(f)
    if user_id not in jar:
        jar[user_id]["cookies"]=0
        with open("jardb.json", "w") as f:
            json.dump(jar, f)
            
    


bot.run(token)```
#

error:

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 18, in on_message
    jar[user_id]["cookies"]=0
KeyError: '988763812272422952'```
crisp thunder
#

are there any differences on using pycord speed compared to using none?
CPU usage wise? o

silk fulcrum
pulsar solstice
#

like what u actually mean

silk fulcrum
#

if user_id not in jar:
jar[user_id]

pulsar solstice
silk fulcrum
pulsar solstice
silk fulcrum
#

if you are trying to set jar[user_id] to something, then do jar[user_id] = something

pulsar solstice
#

ohhh ic ic let me try it

silk fulcrum
#

not jar[user_id]["cookies"]=0

pulsar solstice
silk fulcrum
pulsar solstice
silk fulcrum
pulsar solstice
#

no

#

jar[user_id] = cookies=0

#

i did this

silk fulcrum
pulsar solstice
#

ok done fixed i

#

it*

silk fulcrum
#

jar[user_id] = {"cookies": 0} this would work

pulsar solstice
silk fulcrum
#

or -= for subtract

pulsar solstice
#

MASTER thanks a looot!

#

i think i messed up again

#
from http import cookies
import discord
from discord.ext import commands
import json

bot = commands.Bot(command_prefix=">", intent=discord.Intents.all())

@bot.event
async def on_ready():
    print("JOE TO GOOO...")


@bot.event
async def on_message(message):
    user_id=str(message.author.id)
    with open("jardb.json", "r") as f:
        jar=json.load(f)
    if user_id not in jar:
        jar[user_id] = {"cookies": 0}
        with open("jardb.json", "w") as f:
            json.dump(jar, f)
    else:
        jar[user_id]["cookies"] += 5
        with open("jardb.json", "w") as f:
            json.dump(jar, f)```
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\8ster\Desktop\projects\Discord Bots\Novicookies\main.py", line 23, in on_message
    jar[user_id]["cookies"] += 5
TypeError: 'int' object is not subscriptable```
#

...

short relic
#

anyone knows how can i make a login system; eg. login for a custom role that has some unique perms

silk fulcrum
silk fulcrum
rain olive
silk fulcrum
#

What is this error 😳
It happened after I added self.tree.copy_global_to(guild=discord.Object(id=980346257371455528)) to slash commands setup, but when I remove it, this error is still here
TypeError: Object of type _MissingSentinel is not JSON serializable

cursive barn
#

maximum recursion depth error means your code is calling itself to many times.

silk fulcrum
#

Don't call your code that many times

cursive barn
#

its happening on line 125 whenever you process an answer. What lines 121-125 are essentially doing right now is the following: ```
121: Creates a function called checkinput
122: Wait for a message event and assign it to an object 'antwort'
123-124: Check conditions
125: If conditions met, call checkinput and start at 122 again

lone lichen
#

Someone pls 😂

cursive barn
#

I think either your function names are being overwritten or your indentation is screwy

lone lichen
#

Oh okok

cursive barn
lone lichen
#

Can anyone pop up docs for wait_gor

silk fulcrum
unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cursive barn
#

@slate swan you are calling a function from inside itself, this causes an infinite loop

#

you need to restructure your code a bit to prevent that

lone lichen
# unkempt canyon

@slate swan read this and use check argument instead of the if clause and recursing function afterwards and

cursive barn
#

thats not the error you have. you need to fix the recursion first

vale wing
#

Nested function 😔

cursive barn
#

most of them

lone lichen
#

Read the docs for wait_for and you will see that u can completely avoid recursion

cursive barn
#

something like this to get you started @slate swan ```py
async def check_input(message: discord.Message) -> bool:

Conditional statements, return either True for valid response or False for invalid response

answer = await bot.wait_for('message', check=check_input)

Continue processing answer value

#

notice I placed the two lines on the same indentation level, meaning the wait_for is not called inside of the check_input function, which will prevent the infinite recursion error

lone lichen
lone lichen
cursive barn
#

okay, so you are stilling calling it from inside itself.
Your code has to change more than one line

lone lichen
#

U messed it up because you don’t understand how to use the method because you refuse to read the docs

cursive barn
#

you have to rethink your approach and I provided a hint to get you on a good path for doing so

#

your check_input function is going to just do logic for you. like a filter. outside of that is where the rest of your code is.

cursive barn
#

segregation is really useful in your code in moderation. There is a point where it becomes too much, but a little never hurts.

It helps keep your code clean, organized and easy to read, which in turns allows people to assist you more easily, makes it easier to find errors and troubleshoot. If you have 30 things going on in one function, there could be 30 things wrong. 3-4 or even 7-8 things in one function makes it super easy to pinpoint issues.

lone lichen
silk fulcrum
unkempt canyonBOT
#

copy_global_to(*, guild)```
Copies all global commands to the specified guild.

This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.

Note that this method will *override* pre-existing guild commands that would conflict.
cursive barn
# silk fulcrum anyone?

iirc a couple days ago you were asking for help with a project that violated Discord ToS, so while I would love to help you - I am going to refrain from doing so as to not further assist you in your endeavor

lone lichen
silk fulcrum
#

project that violated Discord ToS,

#

what is violating Discord ToS? Hybrid commands?

silk fulcrum
slate swan
lone lichen
slate swan
lone lichen
#

Do it in constructor

#

Or there is new method

silk fulcrum
slate swan
# silk fulcrum ok

yep and if thats not the case, somethings wrong with your commandtree, you might have some incomplete commands like an empty describe or something

silk fulcrum
slate swan
#

not even the print?

silk fulcrum
#

nope

#

just complete emptyness

slate swan
#

hm check your app commands.then

silk fulcrum
#

wdym?

silk fulcrum
vale wing
#

There's no if

#

Use normal IDE for syntax errors highlighting

#

Pycharm or vsc

silk fulcrum
# silk fulcrum wait, empty describe... I guess in like 3 minutes I'm gonna say I'm super dumb

Yeah I'm dumb, I did not provide description for one option in describe
It was sooo long tho, I already thought it won't print anything as last time.
But there's still a problem @slate swan I added self.tree.copy_global_to(guild=discord.Object(id=980346257371455528)), so slash commands would work only on test server, but they also work on second server where my bot is, I thought they'll be removed from it automatically, or that doesn't work like that?

vale wing
#

Tf is that

#

That looks like sublime text to me

silk fulcrum
vale wing
#

Ofc, I have no idea why people even use it as code editor. They say "plugins". What's the fricking purpose of plugins for literal text editor when you can use a normal IDE

silk fulcrum
lone lichen
#

Send ss of full code

vale wing
#

Redefinition of builtin 😩

lone lichen
#

Whats that else doing there?

vale wing
#

Name it obj man why'd you redefine internal class

#

object is builtin

#

The class from what everything inherits

lone lichen
#

Rename it to obj

#

But that aint the major issue

#

U dont know?

#

Yes

#

😂 It’ s floating there without an if

slate swan
#

hey guys, im wondering how i can send a message to a user when they join my server via my bot, tried searching all over he place and i still have no idea how to send a message to the user when they join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

Use this

#

You gotta know what ur tryna do first

cursive barn
#

instead of using if-else statements, you can just use the @commands.has_role check decorator

#

@commands.has_permissions

lone lichen
#

Yes but there are multiple ways to fix it, the most simple one would be to deleta all the code but thats not what ur trying to do

cursive barn
#

I would suggest reading through the documentation a bit to get a feel for what you can do. Its a great reference material

#

when i started using d.py like 6 years ago I was infuriated at the number of people that told me to "rtfd" - but I can honestly tell you it was the best thing for me to do. It helped me seriously improve the quality of my code more than school or tutorials ever did

lone lichen
#

U should probably read python docs first

cursive barn
#

isn't that just a port of d.py

#

it should have the same basic functionality, maybe called something else

silk fulcrum
#

fork

#

yes, it's almost the same

#

big differences are starting in slash commands

lone lichen
#

It’ s helpful to learn python syntax and oop and bit of asynchronous programming before making bots

slate swan
#

can you use client.event to send a message to a member?

lone lichen
#

How are u picking winners

cursive barn
#

@slate swanit took roughly 38 seconds to find

paper sluice
#

its better to send your code in codeblocks or use the pastbin service

slate swan
lone lichen
glad cradle
lone lichen
slate swan
#

oh ok

#

with that ctx thing?

lone lichen
#

Nope

#

With whatever arguments event has

#

What are u trying to do?

slate swan
#

i just want a welcome message for my members when they join through dms

lone lichen
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

Click on this and read the docs for it

cursive barn
#

@slate swanctx is shorthand for context which is whatever context a command is invoked with.

an event usually has very specific arguments and values passed to it, for instance on_message gets passed a discord.Message object.
Likewise, a on_member_join event gets passed a discord.Member object.

so to answer your question, yes you can send a message inside of an event function, but how you go about doing so varies depending on the event you put it under

lone lichen
#

Whats users?

cursive barn
#

what would the point of a try/except if you just pass over the error.
If you are having trouble with something, it might be better to raise the error to better figure out where things are breaking

#

we aren't going to hand you every solution to every problem you encounter. That will not help you at all. We are here to give you hints and point you in the direction of a solution so that you can arrive there on your own and retain the pathway. The only thing learnt from spoonfeeding is a dependence on others to do everything for you.

I said it might be better to raise your errors to pinpoint where your code was breaking, and I also said that the try/except is just passing over the error. Can you try to figure out what you might need to do from that?

bright grail
#

how to make a bot using python can anyone help, I am a beginner.

placid skiff
#

discord.py and relative forks are not beginner friendly

slate swan
bright grail
bitter karma
#

I also want to make discord bot!

#

How can i build?

placid skiff
glad cradle
tired fern
#

i keep getting this error "discord.ext.commands.errors.CommandNotFound: Command "ban" is not found"

#

I get it whenever i try the: clear , ban , kick command

bitter karma
gentle crescent
cursive barn
placid skiff
#

There isn't any plaltform where you can learn d.py or any other forks from what i know
There is just the documentation and the example on github, that's all you need

placid skiff
bright grail
bitter karma
placid skiff
bright grail
#

heheh, see i am compltely new.

#

but now I have all the basis of python covered, now I wanna make some real stuff.. something of use

placid skiff
#

bruh i don't develop in js

bitter karma
#

I am getting this error

#

🥲

bright grail
#

hi all , A quick newbie question

silk fulcrum
#

this is python server 💀

cursive barn
#

this is the python server mate, and on top of that this is for discord.py related questions. We don't answer js questions

placid skiff
#

i can't help you, and this channel is for discord bot in python D_D

bitter karma
#

😅 ok

bright grail
cursive barn
#

no, thats just a link for a tutorial

bitter karma
placid skiff
#

to make a bot you need to know Python basics, asynchronous programming, OOP concepts and how to read a documentation

cursive barn
#

a quick rundown of python basics. There is a getting started guide on the discord.py rtd once you get going

bright grail
placid skiff
silk fulcrum
placid skiff
silk fulcrum
bright grail
#

I would like to appreciate everyone here. I have been on discord its been like just 2-3 days and guys here are awesome and very helpful

slate swan
#

Anyone know if you can add indents in webhook embeds?

placid skiff
#

\n

slate swan
#

not through python

placid skiff
#

uhm so wdym?

slate swan
#

adding a space

#

like so
Hello?
Yes

#

it doesn't seem to add the spaces

placid skiff
#

try with an invisible character

slate swan
#

ah it works with them

cursive barn
# placid skiff see? Filet does <a:D_D:960909884285648916>

sorry for the late response but I just had to add something -
I started my python career in the d.py server. Anytime you asked a question there, you got the same answer rtfd. It was such a popular response that they actually had a tag for it and just blanketed it on every help channel. I learned really quick to think for myself and work through my own problems. To analyze what I was doing and why I was doing it. Formulating routes to get me from point A to point B.

When I got to this server I vowed to try my absolute hardest to teach people the methods I acquired through learning on my own, while not discouraging them with a simple rtfd which had been done to me so many times. It tends to work pretty well but every once in a while you get someone that doesn't want to spend 2-3 minutes looking at documentation to understand why its not working or how to make it work.

robust fulcrum
#

Guys any command idea for my bot?

cursive barn
#

If I could tell anyone starting out programming or with discord.py or anything, it wouldn't be learn python basics first, or any of your typical answers. I would simply help them learn to think like a programmer. Once you have that skill, everything else falls into place. You learn how to learn and how to apply the knowledge you learn to your code, anything you want to do after that is just building on that foundation

(my apologies for the rant - tl;dr trauma + persistence + brain = good stuff)

silk fulcrum
#

interesting

vale wing
vocal snow
silk fulcrum
#

im glad i've learnt all this (except rtfm) from my dad (idk how but when I just saw docs I started to read them...)

robust fulcrum
vale wing
#

I learned python thrice

cursive barn
# robust fulcrum Guys any command idea for my bot?

my favorite thing to make in discord has always been a leveling system. Not really so much a command but a network of commands. Built one for a popular youtuber once that used an AI based entirely on Harry Potter novels and the Lord of the rings to grade messages and reward varying amounts of xp based on that grade

vale wing
robust fulcrum
#

Whats nerd?

cursive barn
silk fulcrum
#

economy has work :lemao:

crisp thunder
#

does pycord/discord.py send newlines?
context.respond("y\nNewline")
should be

y
Newline
``` or

y\nNewline

just a quick question
Cant afford to test it atm
silk fulcrum
#

at least for me

crisp thunder
silk fulcrum
#

1

crisp thunder
#

alr thanks

cursive barn
# vale wing How does it utilize AI

I had it read random sentences from all the books and analyze different characteristics like vowel count, character/word frequency, word/character count, how many diffrerent subjects there were, predicates and prepositions and all sorts of stuff to train it. Then it would examine a message and evaluate it against the baseline values from the novels and the grade was an 100% - the variances for each characteristic

vale wing
#

Interesting

cursive barn
#

it also doubled as a surprisingly good spam filter 🙂

#

used the same logic later on in a email program

vale wing
#

I have one bot with AI the purpose of which is the antispam lol

cursive barn
#

AI is pretty sweet once you get the hang of it

vale wing
spare urchin
#

can i use nextcord.channel for slash commands in nextcord??
if not what can i use for getting channels in slash commands nextcord??

unkempt canyonBOT
spare urchin
#

no not that

vale wing
#

Then what exactly do you mean

paper sluice
vale wing
#

Permissions v2 or smth

spare urchin
cursive barn
vale wing
spare urchin
#

ok..

vale wing
#

That's pretty cool

cursive barn
vale wing
#

In my antispam bot I use unique characters/words amount with total amount of characters and words and it works fine

cursive barn
#

I like to go overboard

slate swan
#

Guys im getting an unknown interaction error for a slash command im using in nextcord and this shit got me confused as hell

vale wing
#

Recently I tried text generation with tensorflow but it smoke grass with saving the model and I don't have nvidia GPU so it takes a while

robust fulcrum
#

Guys how can I make leveling system in dpy?

#

I want to use sqlite for database

slate swan
robust fulcrum
#

Leveling system like many bots have

#

Messages one

slate swan
#

Oh messages

vale wing
#

You will need a database with table with scores and table with levels

cursive barn
# robust fulcrum Guys how can I make leveling system in dpy?

the basic concept is pretty much just ```
1: Receive Message
2: Get Author of Message
3: Create/Add XP to Record of Author in Database
4: Command to Query Database and see XP for user

^ That is extremely oversimplified, but a good starting point to help you visualize what needs to happen
slate swan
#

Oh y'all doing messages a lot different from how I'd approach it

cursive barn
silk fulcrum
#

4: Check if user has enough to level up
5: If yes, give them next level

slate swan
#

Don't mind the ctx: Interaction field btw

#

I moved from discord py a while back and I didn't feel like changing the variable to interaction

silk fulcrum
slate swan
#

@client.slash_command(name="rostercheck", description="Provides a roster report for every registered franchise", guild_ids=devGuildid)
async def rostercheck(ctx: Interaction):
robust fulcrum
silk fulcrum
slate swan
#

The error triggers where I try sending a embed I created

silk fulcrum
vale wing
slate swan
#

Btw the embed is fine before u ask, becuase i wasnt given an "invalid fields" or whatever it's called

silk fulcrum
cursive barn
slate swan
#

I'm getting it rn

silk fulcrum
#

get bucket, store in Counter

vale wing
#

Pretty sure internally it is still a dict lol

slate swan
#
await ctx.response.send_message(embed=embedyes)```
silk fulcrum
#

well.... it's better)

slate swan
#

I'll show the embed as well

robust fulcrum
vale wing
#

Just higher level implementation of the same thing functionally isn't always better but I am not arguing as I never saw its source

slate swan
#
                embedyes = nextcord.Embed(
                    title="Franchise Ownership Report")
                embedyes.add_field(name="Claimed Franchises", value=normteams2)
                embedyes.add_field(name="Open Franchises", value=freeteams2)
                embedyes.add_field(name="Abandoned Franchises", value="[WIP]")
                embedyes.set_footer(text="Abandoned Franchises just means teams that HAVE MEMBERS on them but without an FO")
              
                await ctx.response.send_message(embed=embedyes)```
#

All the variables were checked and doesn't invalidate the embed

silk fulcrum
#

bruh my nextcord docs aren't loading

slate swan
#

There isn't much different from nextcord and discord

#

Most of the stuff is the same

#

Just changed name

silk fulcrum
#

hmm, seems valid, idk

slate swan
#

Me neither 🤷🤷🤷🤷

robust fulcrum
slate swan
#

Everything was going smoothly and now I'm getting some "unkown interaction" bullshit like what??

#

It's literally under the same async def function

#

And everything else with it

#

Wait holdon I might know

#

@silk fulcrum are you experienced with how slash commands work?

#

If you are Is there like time limit before slash commands are immediately invalid after imitating the command?

silk fulcrum
# robust fulcrum How would i do it?

So, if you are using a cog, that'd be easier cause you can define something like self.lvling_cooldown in __init__ method, but im not sure where is it better to put lvling_cooldown if you are not using cogs. So what you do is you define lvling_cooldown = commands.CooldownMapping.from_cooldown(1, 5, commands.BucketType.user) (1 is messages and 5 is seconds of cooldown) and in on_message you get message bucket like this bucket = lvling_cooldown.get_bucket(message), then you check if there is a rate limit, like this if bucket.update_rate_limit(message.created_at) and if yes, then the user is on cooldown and you do not give him anything

silk fulcrum
#

but here Counter is not required

unkempt canyonBOT
#

discord/ext/commands/cooldowns.py line 95

self._cache: Dict[Any, Cooldown] = {}```
slate swan
vale wing
#

Except as values they use some custom class

slate swan
#

I used asyncio throughout the code a couple times

#

Imma try sleeping the code for 100 seconds

#

And see if it invalidates early

silk fulcrum
vale wing
#

To your preference

slate swan
#

@silk fulcrum yeah there's defintly a time limit on it 😂

silk fulcrum
#

ok

vale wing
#

But as for "faster" I could argue

slate swan
#

I mean I guess it makes sense

#

But like I did it to prevent api bans

#

So it sucks that slashcommands do that

vale wing
tired fern
#

When i try to ban someone it gives me this error

"Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions"

silk fulcrum
slate swan
#

how to use a varibale from an if condition to another one ?

#

@silk fulcrum can you help please ?

silk fulcrum
#

w what?

silk fulcrum
slate swan
#

elif (and i want to use a variable from the if) :

#

is it possible ?

silk fulcrum
#

but what is variable from the if

#

variable cannot be defined in if

#

well, technically it can.. by if var := something

#

but are you really using that?

slate swan
#

no a varibale into the if

silk fulcrum
#

I don't get you

slate swan
#

ok ok i'll try to declare it before

#

!e

if (mas := "uwu"):
     print(mas)```
unkempt canyonBOT
#

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

uwu
paper sluice
placid skiff
#

she has used too much javascript

vale wing
#

Literally any language that uses braces for if conditions

placid skiff
#

yup but lil ash use javascript PepeCryDrink

short relic
slate swan
#

Any command suggestions?

#

I’m out of ideas💀

unkempt canyonBOT
#

secrets.token_urlsafe([nbytes=None])```
Return a random URL-safe text string, containing *nbytes* random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If *nbytes* is `None` or not supplied, a reasonable default is used.

```py
>>> token_urlsafe(16)  
'Drmhze6EPcv0fN_81Bj-nA'
silk fulcrum
#

this is for generating tokens

silk fulcrum
short relic
silk fulcrum
short relic
silk fulcrum
#

!e ```py
import secrets

print(secrets.token_urlsafe(20))```

unkempt canyonBOT
#

@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.

IyNXdDvm_uevQUheIkXNX1mCv-M
short relic
#

how can i use missingrole command error

slate swan
#

SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

test1 = sp.getoutput("command output")
result = test1 + teet2 + test3
embed = ... {eval(result)} ..
#

Why? Is this error

silk fulcrum
#

!e py num = 07 print(num)

unkempt canyonBOT
#

@silk fulcrum :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     num = 07
003 |           ^
004 | SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
slate swan
silk fulcrum
#

do not put zero there

vale wing
#

!e py print(0o67)

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

55
vale wing
#

Sus

slate swan
#

Number

vale wing
#

Are you trying to do math command

short relic
#

Traceback (most recent call last):
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 213, in <module>
@bot.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'
whats this

vale wing
#

No braces for @bot.event

silk fulcrum
#

why so fast(

slate swan
#

why my commands don't want to run , but my events run !

short relic
# vale wing No braces for @bot.event
@bot.event()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRole(1006214471909380257)):
        await ctx.send("error")

wdym no braces i thought i put it

silk fulcrum
#

that's how it works

short relic
short relic
# silk fulcrum just remove `()` from `@bot.event`

when i dont have the required roles it say this
Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 215, in on_command_error
if isinstance(error, commands.MissingRole(1006214471909380257)):
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union

silk fulcrum
short relic
silk fulcrum
#

I did not mean that you have to remove error

#

you compare it, so that was right

short relic
silk fulcrum
#

Method is function for class so I meant that you can't use (), and even more pass something in them

#

it should be just commands.MissingRole

#

without brackets and id

limber bison
#

how can i get req.txt in python ?

short relic
# silk fulcrum Method is function for class so I meant that you can't use `()`, and even more p...
@bot.event
async def on_command_error(ctx, error):
    if isinstance(commands.MissingRole):
        await ctx.send("error")

Traceback (most recent call last):
File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\ADMIN\Desktop\bot discord\cat.py", line 215, in on_command_error
if isinstance(commands.MissingRole):
TypeError: isinstance expected 2 arguments, got 1
what 😭

slate swan
#

hey uhm what's the color code for blending in the sides of embeds

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
heavy folio
#

pass it in isinstance()

slate swan
#

@bot.event
async def on_command_error(ctx, error):
pass

silk fulcrum
slate swan
#

hey uhm what's the color code for blending in the sides of embeds

slate swan
silk fulcrum
slate swan
#

I say for @short relic

silk fulcrum
silk fulcrum
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
silk fulcrum
#

there is color arg

slate swan
short relic
#
@bot.event
async def on_command_error(ctx, error):
    pass
    if isinstance(commands.MissingRole):
        await ctx.send("error")

u mean this///

silk fulcrum
slate swan
slate swan
#

It would be something like this

#

yep ty

#

is Reply considered as message ?

silk fulcrum
slate swan
#

it don't respond

silk fulcrum
#

in dpy reply information is inside message.reference

silk fulcrum
#

code?

slate swan
#

no

#

wait i'll show you

#

this is a message, so the event happens

silk fulcrum
#

hm why not

slate swan
#

but when this is sent

#

the event dont happens

vale wing
#

No clue but I remember having issues with that thing too

silk fulcrum
#

well this is reply to message

vale wing
#

I meant the slash command invoke, my bad english

silk fulcrum
slate swan
#

how to make eval command

vale wing
vale wing
slate swan
slate swan
silk fulcrum
#

💀 !src

slate swan
#

!e

pp
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'pp' is not defined
vale wing
# slate swan ownrr

If you don't need async support you can just use eval, if you do need it then tell me

slate swan
#

a command like that

silk fulcrum
silk fulcrum
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
vale wing
slate swan
#

!paste

slate swan
silk fulcrum
#

!e py eval('print(\'yes\')')

unkempt canyonBOT
#

@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.

yes
silk fulcrum
vale wing
slate swan
#

oh

vale wing
#

A sample exec command with async support

slate swan
#
    nameWithIt =(message.content.split("| "))[1]
    NameOfTransferrer = (nameWithIt.split(" has"))[0]
    TheName = NameOfTransferrer.rstrip(NameOfTransferrer[-1])
    Amount = (message.content.split("$"))[1]
    Quantity = (Amount.split("` to"))[0]
    print (TheName)
    if message.author.id == 282859044593598464 and message.content.startswith("**:moneybag:") == True and message.content.endswith("@IBRO,Niva#6356**") == True : 
      await message.channel.send ("**"+NameOfTransferrer+" send me a 'done' message in the dm**")
      data.remove(Tra.name == TheName)
      data.insert({'name':TheName,'isTransferrer':"Yes",'quantity':Quantity})
  except :
    try :
      dictio = (data.search(Tra.name == message.author.name))[0]
      BoolTra = dictio.get("isTransferrer")

      Dicttt = (data.search(Tra.name == message.author.name))[0]
      IntQua = int(Dicttt.get('quantity'))

      AmountToGet = int(IntQua/1000)
    except :
      data.insert({'name':message.author.name,'isTransferrer':"No", 'quantity':0})
      
    if message.content == "done" and BoolTra == "Yes":

      try: 
        dicofmem=(db.search(Mem.name==message.author.name))[0]
        newww = dicofmem.get('balance')
        newbalance = int(newww) + int(AmountToGet)
        db.remove(Mem.name == message.author.name)
        time.sleep(0.1)
        db.insert ({'name':message.author.name, 'balance':newbalance})
        data.remove (Tra.name == message.author.name)
        data.insert({'name':message.author.name, 'isTransferrer':"No",'quantity':0})
        await message.reply (content="**You transferred "+str(IntQua)+" credits, you got `"+str(AmountToGet)+"$`**")```
slate swan
vale wing
# slate swan yep 🙂

Bro use listeners and split it into several functions, pretty sure you are just doing a lot of stuff linearly

slate swan
vale wing
#

Oh damn looking at this code I see so many bad things but no worries ima tell you about them

vale wing
slate swan
slate swan
#

but really it works

#

tha only thing that doesn't work is on reply

vale wing
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
vale wing
#

What is db.remove(smth == smth), you are basically removing a boolean

vale wing
slate swan
# unkempt canyon

in the course that i seen , they used + in variables addition, without this f and {}

slate swan
vale wing
#

Yeah

slate swan
#

tell me hhow

vale wing
#

Just use exec()

slate swan
#

plezx

vale wing
#

Or eval

slate swan
#

how to send the result and err

vale wing
#

That's only possible with eval (or with my implementation)

heavy folio
vale wing
#

Mine is shorter 😀

heavy folio
#

okay well thats just for reference

#

mines much longer but handles output in different ways

cold tide
#

Do yall think its bad coding on a mobile device?

silk fulcrum
#

me yes

cold tide
#

im getting a new laptop soon but i don't wanna stop coding rn

#

i host bots on mobile anyways :)

#

What laptop should i get ? Anyone have recomendations?

short relic
#

how can i make it so that if they use the command =redeem(code) then they will have some perks

silk fulcrum
#

wdym perks

short relic
#

just like that

silk fulcrum
#

uhmm ctx.author.add_roles

#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
silk fulcrum
#

to give special roles

short relic
heavy folio
silk fulcrum
#

just code

slate swan
#

I have !clear command but for some reason i get rate limited due to this command. Does someone know why this happens?

heavy folio
#

show ur code

slate swan
#

sum() takes at most 2 arguments (7 given)
how can i sum more then 2 args

slate swan
unkempt canyonBOT
#
sum

sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").

Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
slate swan
#

!e

print(sum((1, 2, 3, 4,)))```
unkempt canyonBOT
#

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

10
slate swan
#

How do I get all roles name the user is having?

#
description=ctx.author.roles

Or how do I separate the roles in new line?

lone lichen
#

List comprehension

slate swan
#

with the join method of the str object

limber bison
#

how to install py2

#

??link ?

short relic
#
@bot.command()
async def redeem(ctx, code):
    if code == "deptrainhatsv":
        await ctx.send("key successfully redeemed")
        await ctx.author.add_roles(1006216298562326588)
    else:
        await ctx.send("key not found")

why is it not adding role

cold sonnet
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
cold sonnet
#

why no typehint, anyways

lone lichen
cold sonnet
#

yes

short relic
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

lone lichen
#

!d discord.Guild.get_role

unkempt canyonBOT
#

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

Changed in version 2.0: `role_id` parameter is now positional-only.
lone lichen
#

With this

short relic
# lone lichen !d discord.Guild.get_role
@bot.command()
async def redeem(ctx, code):
    if code == "deptrainhatsv":
        guild = bot.fetch_guild(id)
        role = guild.get_role(id)
        await ctx.send("key successfully redeemed")
        await ctx.author.add_roles(role)
    else:
        await ctx.send("key not found")

can i do like this

slate swan
cerulean solstice
#
Traceback (most recent call last):
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Astro/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Embed' object has no attribute 'set'

i have this error the code is:

@bot.command(aliases=['Avatar'])
async def avatar(ctx, *, member: discord.Member=None):
  member = ctx.author if not member else member
  embed = discord.Embed(title=member.name + "#" + member.discriminator)
  embed.set.image(url=member.avatar_url)
  await ctx.send(embed=embed)
#

pls help?

unkempt canyonBOT
#

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

This function returns the class instance to allow for fluent-style chaining.
cerulean solstice
cerulean solstice
cold sonnet
#

ctx.guild.get_role

short relic
cold sonnet
#

yes

slate swan
cold sonnet
#

oop is like using scythe in brawlhalla

#

everything connects to everything

limber bison
#

i have version 3.7 / how can i update it on linux ?
in my aws instance

short relic
# cold sonnet yes
@bot.command()
async def redeem(ctx, code):
    if code == "deptrainhatsv":
        role = ctx.guild.get_role(1006216298562326588)
        await ctx.send("key successfully redeemed")
        await ctx.author.add_roles(role)
    else:
        await ctx.send("key not found")

didint work 💀

cold sonnet
#

error?

#

I mean it's probably just that that you're the owner of the server and the bot can't add roles to you

short relic
#

and no error

short relic