#discord-bots

1 messages · Page 1067 of 1

slate swan
#

¯_(ツ)_/¯

maiden fable
#

A verified and famous bot (Dyno, ig?) ran an eval to by mistake delete every category in every server or smth. Discord saved most of the servers by changing the token and the damage was only done in a handful of servers

tropic burrow
#
import motor
import discord
from webserver import keep_alive
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
import json
from motor.motor_asyncio import AsyncIOMotorClient

with open("./data.json") as file:
  data = json.load(file)

cluster = AsyncIOMotorClient(data['mongo-uri'])
db = cluster["main"]
cursor = db["tutorial"]


client = commands.Bot(command_prefix = "-monkey ")


@client.command()
async def identity(ctx):

  check = await cursor.find_one({"id": ctx.author.id})

  if check is None:
    insert = {
      "id": ctx.author.id, "name": ctx.author.name, "tags": ctx.author.discriminator, "monkeybux": 50
    }

    await cursor.insert_one(insert)

    mbed = discord.Embed(
      title="NOW YOU ARE OFFICALLY REGISTERED AS A MONKEY",
      description="be a good monkey ok"
    )
    await ctx.channel.send(embed=mbed)
  else:
      mbed = discord.Embed(
        title="YOU ALREADY ARE A MONKEY...",
        description="bro you cant have 2 personalities"
      )
      await ctx.channel.send(embed=mbed)
slate swan
#

How do you install pycord on replit?

tropic burrow
#

it auto installs... There is package manager

maiden fable
potent spear
slate swan
maiden fable
slate swan
maiden fable
#

Weird

slate swan
slate swan
maiden fable
slate swan
#

who names their dir as mainfile.py in the first place....

#

Oh wait thats a directory

heady sluice
slate swan
#

I was wondering how he placed jpg in py file lol

terse coyote
#

how to make it so that only one member can use the discord_components button

slate swan
#

and its better to use os.path and make dynamic paths when hosting

#

since the hosting service seems to run in a docker container

slate swan
#

and better upgrade to dpy 2.0

#

Also either keep the same dirtree as in development or use dynamic paths, yes

#

Those both folder structures are completely different

slate swan
#

hardcoding the paths wont work most of the times

#

since the directory could be located anywhere and the program could be run from any directory

robust fulcrum
#
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def clean(ctx, limit: int):
	await ctx.channel.purge(limit=limit)
    await ctx.send('Cleared by {}'.format(ctx.author.mention))
	await asyncio.sleep(3)
    await ctx.message.delete()

It's says indentation error
But my indentation is correct
Do anyone know how to fix?

terse coyote
robust fulcrum
#

Bit still error

slate swan
#

!pip discord_components

unkempt canyonBOT
robust fulcrum
maiden fable
#

BTW u can use the delete_after kwarg in ctx.send to delete the message after x seconds

robust fulcrum
#

No prob but how to fix error

robust fulcrum
terse coyote
slate swan
# terse coyote how?
def check(inter):
     return inter.author.id == command_invoker.id
await bot.wait_for("button_click", check=check)```
or use lambda
slate swan
robust fulcrum
robust fulcrum
maiden fable
#

Uh tell me smth...

slate swan
maiden fable
#

Oh author, nvm

robust fulcrum
slate swan
robust fulcrum
#

💩

maiden fable
#

Nice token

slate swan
maiden fable
#

@robust fulcrum

tough lance
robust fulcrum
slate swan
slate swan
robust fulcrum
#

Ok i refresh

robust fulcrum
slate swan
#

oh you copied nvm

robust fulcrum
#

Replit is a dumb

slate swan
#

its not

#

every ide does that

robust fulcrum
#

Bruh but replit pip is annoying

slate swan
#

...?

robust fulcrum
#

I downloaded discord.py 2.0 but it changed it to 1.7

tough lance
#

Bruh just erase the code and write it yourself

robust fulcrum
#

Lazt

#

Lazy

winged bone
#

Replit has nothing to do with pip

#

They don't have their own pip

slate swan
tough lance
slate swan
#

shell*

tough lance
#

You can say

slate swan
#

it is named as shell

tough lance
#

Ok

winged bone
tough lance
#

You can install packages in replit and it is done through pip

winged bone
#

Yes

maiden fable
#

Imagine talking about replit

slate swan
#

imagine hating it

winged bone
#

Maybe I phrased it wrong, of course replit has something to do with pip, because you can use it there. But they don't mess with the source code of pip, pip was made by other people

#

So when something doesn't work with pip, you can't blame replit

tough lance
paper sluice
#

whats wrong with replit's pip?

tough lance
#

Nothing

robust fulcrum
slate swan
slate swan
robust fulcrum
#

Ok

slate swan
#

poor hunter gets ignored

winged bone
#

What about GitHub codespaces? I saw that you can get them for free anywhere

paper sluice
#

u can't run your code there

#

its just for editing

winged bone
#

With the paid version you can

maiden fable
paper sluice
#

o.o

winged bone
sick kettle
robust fulcrum
sick kettle
#

ye

winged bone
sick kettle
#

doesnt toml file work with githubtoo

vale wing
#

Why even use replit for bots 😩

#

Don't yall have a PC which you can install some IDE on

placid skiff
sick kettle
#

why would someone use replit for ide unless 😳

vale wing
#

Imagine

placid skiff
#

like someone would really go live a bot hosted with replit D_D

sick kettle
#

ppl do a lot actually

vale wing
#

And then be like "why tf I receive 429 errors"

slate swan
#

Can someone please explain to me why my bot said "ISRAEL helper 💯" as its name in dms? 💀 I got the code of a friend

placid skiff
#

exceptions in replit are like exceptions in java

#

just a huge mess of message without any sense

sick kettle
#

oh wait its display_name

vale wing
#

@slate swan do you have members intent

vale wing
vale wing
slate swan
vale wing
#

Ok show how you define intents in code

placid skiff
#

I spent last 4 days working on a project
And today the customer i'm working for decided to change the input data D_D

sick kettle
#

looks good to me

vale wing
#

Ok seems valid

slate swan
#

well then i guess i have to add if the bot is mentioned it says Admin Helper? Instead of member.display_name?

sick kettle
#

show bots profile

vale wing
sick kettle
#

i cant really think of why the display_name is like that

vale wing
#

@slate swan anyway try to print member.nick and member.name

placid skiff
#

Member can have a guild nickname, display_name will return the guild name if a guild name is set

#

nick will return his guild name, but it could be None

#

name will return the User name

vale wing
#

Yes but in this case the member does have a guild nickname

#

And that's what is weird

slate swan
#

Well i just added if its not in an guild it sends it like normal but it says "My avatar" and it works!

flint isle
#

    @commands.slash_command(name='test', guild_ids=config)
    async def permissions(self, inter, heh):
        embed = disnake.Embed
        embed.title(title="Bot Permissions")
        embed.set_footer('❤ Made with Love ❤')
        embed.description('e')
        message = await inter.channel.send(embed=embed)
        time.sleep(2)
        new_embed = message.embed[0]  # Message.embeds returns a list, so just index the first element
        new_embed.description += "UwU"
        time.sleep(2)
        new_embeded = message.embed[0]
        new_embeded.description += f"heh"
        await message.edit(embed=new_embed)
#
Ignoring exception in slash command 'test':
Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 680, in invoke
    await call_param_func(self.callback, inter, self.cog, **kwargs)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\params.py", line 817, in call_param_func
    return await maybe_coroutine(safe_call, function, **kwargs)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 580, in maybe_coroutine
    return await value
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\aboutme.py", line 36, in permissions
    embed.title(title="Bot Permissions")
TypeError: 'member_descriptor' object is not callable

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

Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1264, in process_application_commands
    await app_command.invoke(interaction)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 689, in invoke
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'member_descriptor' object is not callable
slate swan
#

embed = disnake.Embed()

flint isle
#

omg did i forget the parentesis

#

🤦‍♂️

flint isle
# slate swan embed = disnake.Embed`()`

now i have


Ignoring exception in slash command 'test':
Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 680, in invoke
    await call_param_func(self.callback, inter, self.cog, **kwargs)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\params.py", line 817, in call_param_func
    return await maybe_coroutine(safe_call, function, **kwargs)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 580, in maybe_coroutine
    return await value
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\aboutme.py", line 36, in permissions
    embed.title("Bot Permissions")
TypeError: '_EmptyEmbed' object is not callable

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

Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1264, in process_application_commands
    await app_command.invoke(interaction)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 689, in invoke
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '_EmptyEmbed' object is not callable
paper sluice
#

just do Embed(title=..., description=...)

flint isle
#

ahhh. im trying to edit the description later on in code. how can i do that

slate swan
#

same goes for description

potent spear
#

shortest method

embed = ...
msg = await channel.send(embed=embed)
embed.description = "shit"
await msg.edit(embed=embed)```
robust fulcrum
#

Guys how can we make seprate files for every comamnd?

placid skiff
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to
help group commands together. More information on them can be found on
the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta")
are equally valid here.
slate swan
#

Is there a discord2.0?

robust fulcrum
tropic burrow
#
import motor
import discord
from webserver import keep_alive
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
import json
from motor.motor_asyncio import AsyncIOMotorClient

with open("./data.json") as file:
  data = json.load(file)

cluster = AsyncIOMotorClient(data['mongo-uri'])
db = cluster["main"]
cursor = db["tutorial"]

in replit what am i supposed to put in the json file to make this work (i am refering to data.json

slate swan
#

BlvckTvrsier, by any chance do you know why my bot cannot detect messages on threads?

digital mason
#

Hello I have a question

slate swan
#

Someone told me its because of d.py 1.7.3 but it works in 2.0 but what exactly is 2,.0?

slate swan
#

its the master ( still in development ) branch of Discord.py

#

tou can install it using git

tropic burrow
#

what do i put in it

slate swan
#

And does it include slash command, buttons and such?

placid skiff
#

py -m pip install git+[github_link]

#

you need git installed for this to work

slate swan
#

You too @slate swan

slate swan
#

Nice!

slate swan
tropic burrow
potent spear
#

you'll need these things

#

!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...
potent spear
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji")...
potent spear
#

!d discord.Message.remove_reaction

unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji")...
potent spear
#

there you go, gl!

dawn shard
#

Can't you just do ctx.guild.leave

slate swan
#

you can take an guild argument from the user ( discord.Guild typehint )

#

!d discord.Guild.leave and use this

unkempt canyonBOT
#

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

Leaves the guild...
warped mirage
#

Can someone help me make this ?

slate swan
placid skiff
#

!d discord.ext.commands.Bot.is_owner

unkempt canyonBOT
#

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

Checks if a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") or [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") is the owner of
this bot.

If an [`owner_id`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.owner_id "discord.ext.commands.Bot.owner_id") is not set, it is fetched automatically
through the use of [`application_info()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.application_info "discord.ext.commands.Bot.application_info")...
slate swan
#

!d discord.ext.commands.GuildConverter

unkempt canyonBOT
#

class discord.ext.commands.GuildConverter(*args, **kwargs)```
Converts to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

The lookup strategy is as follows (in order):

1. Lookup by ID.

2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names)...
slate swan
#

this Exists

tropic burrow
#

hey guys how do you ref a json file in replit

maiden fable
#

Yes

maiden fable
tropic burrow
maiden fable
#

Sure

slate swan
#

if the file is in the same directory, yes

slate swan
slate swan
slate swan
#

depends on ur file structure tbh

slate swan
#

why does it work for me

slate swan
#

uhuh

robust fulcrum
#

Guys anyone here know how can we make a command that a user can use only once in 12 hours like vote command

placid skiff
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount
of times in a specific time frame. These cooldowns can be based
either on a per-guild, per-channel, per-user, per-role or global basis.
Denoted by the third argument of `type` which must be of enum
type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType")...
placid skiff
#

Hi Ash

robust fulcrum
placid skiff
#

Read the docs... it explains how it works

flint isle
#

I'm using Disnake how can I add a field to a embed

torn sail
#

!d disnake.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.
tropic burrow
#

why does the balance not increase at all:


async def open_acccount(user):
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  else:
      users[str(user.id)] = {}
      users[str(user.id)]["wallet"] = 0
      users[str(user.id)]["bank"] = 0

  with open("./data.json","w") as f:
    json.dump(users, f)
  return True
    
async def get_bank_data():
  with open("./data.json","r") as f:
    users = json.load(f)

  return users

client.command()
@commands.cooldown(1,15,commands.BucketType.user)
async def beg(ctx):
  await open_acccount(ctx.author)

  users = await get_bank_data()
  user = ctx.author
  earnings = random.randint(0,100)



  mbed = discord.Embed(
    title="You beg other monkes for monkeybux...",
    description=f"and get {earnings} monkeybux!"
  )
  await ctx.channel.send(embed=mbed)

  users[str(user.id)]["wallet"] += earnings
halcyon onyx
#

wait ill read that

tropic burrow
#

this is the problem

halcyon onyx
#

the return always 0

#

?

dim wing
#

Hi, i would like to acces to my rsp pi (with linux) and control it via a discord bot, do you think it could be possible?

tropic burrow
halcyon onyx
dim wing
tropic burrow
#

so my best bet was json

halcyon onyx
tropic burrow
#

nothing happens to json

halcyon onyx
#

i will code it wait a minute

tropic burrow
#

{"user": {"wallet": 0, "bank": 0}, "user": {"wallet": 0, "bank": 0}, "user": {"wallet": 0, "bank": 0}}

#

user is the user id

#

thats the json file after begging (3 ppl used the command)

quaint epoch
#

👃 I smell dank memer clones lemon_glass

slate swan
flint isle
tropic burrow
#

just did not share it

flint isle
#

Ok... that's why I was asking lol

slate swan
slate swan
hazy schooner
#

Does anyone knows a professional discord.py developer?

slate swan
#

theres no professional dpy dev lmao

#

this isnt a profession

#

i think you ment experienced?

hazy schooner
#

Haha I am making it a profession with my business

hazy schooner
slate swan
#

well if you have questions yes theres many here

#

especially ash😳

hazy schooner
#

👀

tropic burrow
hazy schooner
#

I have a big project in development if you have any specific recommendations

slate swan
#

no

#

ash youre the best 🙏

slate swan
#

why am I always the center of embarrassment

#

omg😭

hazy schooner
slate swan
#

ah cool

hazy schooner
#

Yeh if you know anyone who would be interested pls lmk 😊

tropic burrow
# halcyon onyx ok now we know where the issue is

i think i found the issue


async def open_acccount(user):
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  else:
      users[str(user.id)] = {}
      users[str(user.id)]["wallet"] = 0
      users[str(user.id)]["bank"] = 0

for someone reason the if condition is false

#

then the values get reseted to 0

slate swan
slate swan
hazy schooner
slate swan
#

👍

shrewd apex
tropic burrow
#

k

vast lark
#

@shrewd apex so... can we dm?

hazy schooner
tropic burrow
#
async def open_acccount(user):
  users = await get_bank_data()

  if str(user.id) in users:
    return False
  
      users[str(user.id)] = {}
      users[str(user.id)]["wallet"] = 0
      users[str(user.id)]["bank"] = 0

  with open("./data.json","w") as f:
    json.dump(users, f)
  return True
    
async def get_bank_data():
  with open("./data.json","r") as f:
    users = json.load(f)

  return users

it returns true

#

when the condition is false

#

so return await?

shrewd apex
tropic burrow
#

nah that was a mistake

#

when copying my code

shrewd apex
#

as i said u don't need the else u can remove that and stick everything to the side

#

rest will work as it is return True is not particularly required either

vast lark
#

ehmm... k.... I don't know nothing about phyton, or programming in general... do you know were to start to create a bot that combines dyno's moderation and mee6? @shrewd apex

shrewd apex
#

also i wouldn't use json in cases for storing and frequent usage of data i would use sql i personally use postgres

tropic burrow
shrewd apex
#

idk abt using replit so can't comment on that u can try mongodb tho it's pretty similar to jsons

edgy sky
#

that text

#

wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')

tropic burrow
#

"```"

edgy sky
#

"wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')"

tropic burrow
#

no

shrewd apex
tropic burrow
#

like

shrewd apex
tropic burrow
#

yes

edgy sky
#

"'wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')'"

shrewd apex
edgy sky
#

'''wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')'''

shrewd apex
#

back stick lmao

#

' `

edgy sky
#
wn.onkey(lambda: t1.setheading(0), 'Right')```
tropic burrow
#

put py

edgy sky
#

YAY!

tropic burrow
#

after the three

shrewd apex
#

lmao u used only 1 `

edgy sky
#
wn.onkey(lambda: t1.setheading(180), 'Left')
wn.onkey(lambda: t1.setheading(0), 'Right')```
#

YOOOOOO

#

ty

tropic burrow
#

@shrewd apex
will this work


async def update_bank_data(user,change = 0,mode = "wallet"):
  users = await get_bank_data()

  users[str(user.id)][mode] += change

  with open("./data.json","w") as f:
    json.dump(users, f)

  bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
  return bal
  
#

i wil call it to update the balance

light violet
#

.

slate swan
#

how to make all commands only work for certain guild.id

vale wing
wet crystal
#

but what does Role look like

#

its not the string name

#

i think at least

slate swan
#

its a object

#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild")...
wet crystal
#

why does this return this error when in a Voice channel?

Command raised an exception: AttributeError: 'int' object has no attribute 'isnumeric'

when I am not connected it returns this error:

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'

code:

@bot.command()
async def roulette(ctx):
    VoiceID = ctx.author.voice.channel.id
    voicemembers = nextcord.VoiceChannel.members

    if VoiceID.isnumeric():
         shuffeledvms = random.shuffle(voicemembers)
         randvm = random.choice(shuffeledvms)
         shuffeledvms.move_to(None)
    else:
        await ctx.send("You need to be in a voice channel!")
wet crystal
warped mirage
#

Can someone help me make this ?

wet crystal
#

but ill send u something

warped mirage
wet crystal
warped mirage
#

And u don’t have to answer , I have people who don’t mind answering

wet crystal
unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
slate swan
#

you gotta utilise the discord.ui.View class and use View.add_item(discord.ui.Button(**kwargs))

warped mirage
#

I know how to make commands

wet crystal
slate swan
warped mirage
# wet crystal great, then go for it

This what I showed is a trivia system , which means I need certain packages and a difficulty , for example trivia easy , trivia medium , trivia hard

#

That’s my main problem

wet crystal
warped mirage
#

Ok

wet crystal
potent spear
#

don't tell me you watched a YT video about this

slate swan
#

wish there was a ?tag lucas unban here

potent spear
#

equally as bad mostly

#

this sucks

#

ctrl +f unban in this channel

#

this has been solved many times before

slate swan
#

you forgot the async keyword

#

its an async iterator

#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list...
slate swan
#

Is your unban command looking like this?

    for ban_entry in banned_users:
         user = ban_entry.banned_users

         if (user.name, user.discriminator) == (member_name, member_discriminator):
             ...

Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:

# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))

# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None): 

Inspiration from d.py official server

also, this ^

terse coyote
#

how to delete bot's message after button click?

slate swan
#

🍿

spring flax
#

Can you edit other users messgae to add spoilers to it?

slate swan
warped mirage
#

bw guys how can i fix this py winner = random.choice(users) File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice return seq[self._randbelow(len(seq))] IndexError: list index out of range

slate swan
#

because it doesnt exist

warped mirage
terse coyote
warped mirage
#

so how do i fix it where do i index the list

slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | IndexError: list index out of range
slate swan
#

this is what causes the error

#

moderate_members=True

warped mirage
#
 questionList =[
            ["What channel should it be in?", "Mention the channel"],
            ["How long should this giveaway last?", "d|h|m|s"],
            ["What are you giving away?", "E.G. Pizza"]
        ]
        answers = {}``` this ?
warped mirage
slate swan
# terse coyote

store the message in an var and use the delete method in it

msg = await ctx.send(...)
//wait for the button click maybe
await msg.delete()
#

yes

#

yes

warped mirage
#
 questionList =[
            ["What channel should it be in?", "Mention the channel"],
            ["How long should this giveaway last?", "d|h|m|s"],
            ["What are you giving away?", "E.G. Pizza"]
        ]
        answers = {}``` this ?
slate swan
#

?

warped mirage
#

where do i index

slate swan
slate swan
slate swan
warped mirage
#
winner = random.choice(users)``` so what now
slate swan
wet crystal
#

what is wrong with this variable?

VoiceID = ctx.author.voice.channel.id

it returns this:

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'

warped mirage
#
winner = random.choice(users)``` can someone tell me how do i fix this
#

ah lemme search on google

slate swan
slate swan
warped mirage
#

ill just send code

slate swan
#

!d discord.Member.voice

unkempt canyonBOT
slate swan
#

idk why people donteventryto understandtheerror that is caused by theircode

warped mirage
slate swan
#

i love your point but that wording is just😭

slate swan
#

i see that😭

slate swan
# slate swan i see that😭

no offence but for a second you really made me feel like - "what am I even writing...is that even english", ngl

#

😔

warped mirage
#

so does anyone know how to fix my code , its multiguild

sick birch
slate swan
#

Robin is so smort

warped mirage
#

lmao seems like my error is impossible to fix xd

#

.

slate swan
warped mirage
#

am i muted or something , brb

#

ill just explain in messages.

#
giveaway.py has been loaded
Ignoring exception in command giveaway:
Traceback (most recent call last):
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Dom\Desktop\beta test\cogs\giveaway.py", line 104, in giveaway
    winner = random.choice(users)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range``` this is my error , how do i fix it
sick birch
#

am the big smart

warped mirage
#

yo robin can u help me

sick birch
#

I can try

warped mirage
#

ok

sick birch
#

Well the error is self explanatory is it not

slate swan
sick birch
#

Only cause of the error might be that user is empty

warped mirage
#
try:
            reaction, member = await self.client.wait_for(
                "reaction_add",
                timeout=60,
                check=lambda reaction, user: user == ctx.author
                and reaction.message.channel == ctx.channel``` i have this
slate swan
sick birch
#

In your on message, check if the message.content == bot.user.mention

#

If so, send something

warped mirage
#

Oh wait i see the problem

#
users.pop(users.index(ctx.guild.me))``` this right?
sick birch
#

Try printing it out to be sure

sick birch
#

Yeah, try printing the list of reactions

warped mirage
#

so what do i do.

#

like where

sick birch
#

after the wait for

#

Actually never mind

warped mirage
#
try:
            reaction, member = await self.client.wait_for(
                "reaction_add",
                timeout=60,
                check=lambda reaction, user: user == ctx.author
                and reaction.message.channel == ctx.channel
            )
            print(reaction)``` like this?
sick birch
#

Print users

#

After the asyncio sleep

#

Right before the users.pop

warped mirage
vapid grove
#

How to set this type of slash command in the nextcord?

warped mirage
#
[<Member id=975835075784617994 name='Beta Testing' discriminator='9566' bot=True nick='FROZENFUT LEVEL SYSTEM' guild=<Guild id=942487587602456617 name='FrozenFut' shard_id=None chunked=True member_count=8104>>, <Member id=944343972258648115 name='MasterKnots' discriminator='9999' bot=False nick=None guild=<Guild id=942487587602456617 name='FrozenFut' shard_id=None chunked=True member_count=8104>>]
[<Member id=975835075784617994 name='Beta Testing' discriminator='9566' bot=True nick=None guild=<Guild id=975835154029355029 name='Beta Testing Support' shard_id=None chunked=True member_count=20>>, <Member id=944343972258648115 name='MasterKnots' discriminator='9999' bot=False nick=None guild=<Guild id=975835154029355029 name='Beta Testing Support' shard_id=None chunked=True member_count=20>>]``` guys this showed up , is this bad?
wet crystal
#
@bot.command()
async def roulette(ctx):
    try:
        VoiceID = ctx.author.voice.channel.id
        vms = []    
        voicemembers = nextcord.VoiceChannel.members
        vms.append(voicemembers)
        print(vms) # print is for debug reasons
        if len(vms) <= 0:
            return
        elif len(vms) == 1:
            await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
        else:
            VoiceID = ctx.author.voice.channel.id
            randvm = random.choice(vms)        
            randvm.move_to(None)
    except:
        await ctx.send("You need to join a Voicechannel!")

There are 2 users in the Voice Channel.
Why doesn't it add both members to the list?

warped mirage
#

yep it logs the users now

torn sail
wet crystal
torn sail
#

not nextcord.VoiceChannel.members. you can get it with ctx.author.voice.channel.members

wet crystal
slate swan
#

thats just a list of member objects

#

its formatted like that because of the Member class's __repr__

torn sail
wet crystal
# torn sail show updated code. also `len(vms)` will always be `1` because you are adding the...
@bot.command()
async def roulette(ctx):
    try:
        VoiceID = ctx.author.voice.channel.id
        vms = []    
        voicemembers = ctx.author.voice.channel.members
        vms.append(voicemembers)
        print(voicemembers)
        if len(vms) <= 0:
            return
        elif len(vms) == 1:
            await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
        else:
            VoiceID = ctx.author.voice.channel.id
            randvm = random.choice(vms)        
            randvm.move_to(None)
    except:
        await ctx.send("You need to join a Voicechannel!")
torn sail
#

yeah you should just use voicemembers

wet crystal
torn sail
#

hmm im not sure why the list is empty

wet crystal
#

neither am I

#
@bot.command()
async def roulette(ctx):
    try:
        VoiceID = ctx.author.voice.channel.id
        voicemembers = ctx.author.voice.channel.members
        print(voicemembers)
        if len(voicemembers) <= 0:
            "List is empty"
        elif len(voicemembers) == 1:
            await ctx.send("Bro...You are alone why would you want to play Russian roulette by yourself?\nGo get a friend!")
        else:
            randvm = random.choice(voicemembers)        
            randvm.move_to(None)
    except:
        await ctx.send("You need to join a Voicechannel!")

code rn

wet crystal
#

u always need to add await b4 ctx right?

#

nvm

#

forget waht I said

young pike
#

Hello, Coders!
How to make localization to slash commands? I am usin' nextcord, but I can switch to smth else (except discord.py and pycord)

slate swan
#

green, primary is blue

young pike
#

This is just an idea

#

import ButtonStyle

#

so how do u use it?
can you send me some screenshots

#

from discord import ButtonStyle
@slate swan

slate swan
#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
slate swan
#

^

#

i wonder why that class isnt limited to the ui folder

#

same thought but the question is automatically answered when you remember that you're talking about discord.py

#

😭

young pike
#

guys

#

I still have the same problem 'bout localizationpython

wet crystal
latent sable
#

how to do this in python
someone will send a message and reply to him on the bot but without prefix

tacit token
#

@client.event
async def on_message_edit(before,after):
    channel=client.get_channel()
    embed=discord.Embed(color=0x123456)
    embed.set_author(name=f"{before.member.name}", icon_url=before.member.name.avatar_url)
    embed.add_field(name=f"Előtte",value=f"{before.content}", inline=True)
    embed.add_field(name=f"Utána",value=f"{after.content}", inline=True)
    await channel.send(embed=embed)

AttributeError: 'Message' object has no attribute 'member'

tacit token
#

nope

latent sable
#

./

heady sluice
#

also, what formatting is this

tacit token
heady sluice
#

and why do you use these f-strings 😭

tacit token
#

i love it

heady sluice
#

but they're useless in this case

#

all of them

tacit token
#

ik

#

but i use this for everything

heady sluice
#

but it's memory loss

tacit token
#

yap

tacit token
#

and how can i mention the channel where edited this message with the after/before

#

fixed

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled...
warped mirage
#
@commands.command()
    async def slowmode(ctx,time:int):
        if (not ctx.author.has_permissions.manage_messages):
            await ctx.send('This command requires ``Manage Messages``')
            return
        try:
            if time == 0:
                await ctx.send('Slowmode turned off')
                await ctx.channel.edit(slowmode_delay = 0)
            elif time > 21600:
                await ctx.send('You cannot set the slowmode above 6 hours!')
                return
            else:
                await ctx.edit(slowmode_delay = time)
                await ctx.send(f'Slowmode set to {time} seconds!')
        except Exception:
            await print('Hmmmm..')```
#
if (not ctx.author.has_permissions.manage_messages):
AttributeError: 'slowmode' object has no attribute 'author'```
halcyon onyx
#

anyone have way to import all cogs automaticly without importing one by one

weak moat
#

Can you tell me how to calculate the list coin = ['COIN', 'ASCOIN'] and if the user enters the command .coin COIN it checks if there is an intersection point after .coin in the list and outputs either a runtime error actions

heavy shard
#

what's wrong with adding cogs manually?

#

wait, you mean loading extensions, right?

warped mirage
#

@heavy shard

#

can u tell me whats wrong with this code

#
@commands.command()
    async def slowmode(ctx,time:int):
        if (not ctx.author.has_permissions.manage_messages):
            await ctx.send('This command requires ``Manage Messages``')
            return
        try:
            if time == 0:
                await ctx.send('Slowmode turned off')
                await ctx.channel.edit(slowmode_delay = 0)
            elif time > 21600:
                await ctx.send('You cannot set the slowmode above 6 hours!')
                return
            else:
                await ctx.edit(slowmode_delay = time)
                await ctx.send(f'Slowmode set to {time} seconds!')
        except Exception:
            await print('Hmmmm..')```
livid hinge
#

i noticed something annoying about discord ||for android||

heavy shard
livid hinge
#

the time thing doesnt tick down -.-

livid hinge
#

<t:1234567890:R>

heavy shard
#

says "13 years ago" here

warped mirage
#
File "C:\Users\Dom\Desktop\beta test\cogs\slowmode.py", line 11, in slowmode
    if (not ctx.author.has_permissions.manage_messages):
AttributeError: 'slowmode' object has no attribute 'author'```
#

13 years ago

#

|| hello ||

heavy shard
livid hinge
#

<t:1653681340:R>

livid hinge
#

there we go

heavy shard
#

and the error says something like ctx is slowmode class, which means you skipped/forgot first argument, which is self

livid hinge
#

on android it's just stuck lol

heavy shard
#

async def slowmode(self,ctx,time:int):

livid hinge
heavy shard
livid hinge
#

yeah that would be sick

warped mirage
livid hinge
#

what i was doing is sending a message with a timestamp tag of X seconds in the future and delete_after=X

#

then the code does asyncio.sleep(X) and then sends whatever

heavy shard
heady sluice
livid hinge
#

because the API i use has a estimated_time in responses when its not yet ready

livid hinge
#

i thought of using a task to edit the message every second but that seemed like too much work

heavy shard
#

ctx.channel.permissions_for(ctx.author).manage_messages

livid hinge
#

is it commands.has_permissions ?

heady sluice
#

that's a decorator

#

error handling for that is a bit harder than what he does

terse coyote
#

can i do while in while?

heady sluice
#

but it would work for every command

livid hinge
#

thats not how they want to do it ?

heady sluice
#

I don't think so

heavy shard
livid hinge
#

you just cant continue or break the outer loops from the inner loop which is a bit lacking

heady sluice
#

actually, what does has_permissions raise?

#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of
the permissions necessary.

Note that this check operates on the current channel permissions, not the
guild wide permissions.

The permissions passed in must be exactly like the properties shown under
[`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions")...
heady sluice
slate swan
heady sluice
#

!d discord.ext.commands.MissingPermissions.missing_permissions he could even handle it and get the same results

unkempt canyonBOT
heady sluice
#

and he wouldn't have to do the same for every command

slate swan
slate swan
terse coyote
#

File "c:\Users\gramo\OneDrive\Робочий стіл\Bot\server.py", line 156, in report
await reportchannel.set_permissions(roleforum, delete_messages = True)
File "C:\Program Files\Python310\lib\site-packages\discord\abc.py", line 648, in set_permissions
raise InvalidArgument('target parameter must be either Member or Role')
discord.errors.InvalidArgument: target parameter must be either Member or Role

slate swan
#

no role with that ID exists, or you dont have role intents

slate swan
slate swan
#

ButtonStyles are literally just numbers

#

thats like having Intents inside the client.py since you need them for making it

#

what?

#

you make no sense? im literally having a stroke trying to comprehend your point.

#

thats why you should check the complete file paths and all the places where that class has been used before making a comment on the library

#

!d discord.ui.Button.style

unkempt canyonBOT
slate swan
#

so you want it to return a discord.ui.ButtonStyle?

#

well it seems like you didnt quite read my comment🤔

#

i wonder why that class isnt limited to the ui folder (edited)

#

"limited"

#

elaborate what do you mean by limited?

#

its namespace

#

so you mean it should be discord.ui.ButtonStyle?

#

limited to that namespace? that is so.

#

iwonder why the slash commands dont show up

#

no more

#

when i tried bot.slash_commands i got this ['invite', 'bump', 'remove', 'add', 'help', 'botinfo', 'preview', 'setup', 'unload', 'check', 'vote'] but

slate swan
slate swan
#

just have an enum file for each folder? so each enum is set to its category where it falls in?

#

😂

slate swan
slate swan
slate swan
slate swan
slate swan
# slate swan whats so funny?

a file, for a single class? the enum for which is not just being used in that folder but the root folder too, why?

#

there's a discord.Button class, which uses that enum too, and no it does not lie inside the ui folder

slate swan
#

so you would be py from .ui.enums import ButtonStyle instead of py from .enums import ButtonStyle not fair

slate swan
#

exactly thats my point.

#

well, im too unqualified to explain this, try discussing it with someone who actually helped in designing the libary

#

but in my opinion, the abstraction is perfect.

#

🤷‍♂️

#

btw, look into the source code, they use discord.Button ( components.py) to make discord.ui.Button(ui/buttons.py) 😂 lets blame them for this too.

slate swan
#

thats what i was saying for the time being. they derive the constructor classed from base classes

#

so keeping the enum limited to the ui folder wont make any sense

#

the component.py file shouldnt even be in the parent folder it should be in the ui folder

#

again, ask them not me lmao

#

i wasnt asking you thoshipit

warped mirage
#

guys

#

can someone suggest me on what can i code for my bot

lyric grove
#

Sheshead.

heavy shard
#

polls maybe

steep drift
#

Hey!

#

I need some more help with a bot

#

different bot

#

For some reason this ranking bot doesn't work that I made; also I don't know how you would add a command to get your level and a leaderboard of the top 10 highest leveled people.

#

Here is the script.

#
from discord.ext import commands
import json
import discord
import os
import random
import time

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

#On Ready Event.
@client.event
async def on_ready():
  print("Bot Ready.")
  time.sleep(1)
  print("Logged In As:  {0.user}".format(client))

#Function For Getting A Users Information And Level Them Up.
@client.event
async def on_member_join(member):
  with open("users.json", "r") as f:
    users = json.load(f)

  await update_data(users, member)

  with open("users.json", "w") as f:
    json.dump(users, f)

#Function For Sending Messages.
@client.event
async def on_message(message):
  with open("users.json", "r") as f:
    users = json.load(f)

  #amount_of_experience = float(randint(1, 5))

  await update_data(users, message.author)
  await add_experience(users, message.author, 5)
  await level_up(users, message.author, message.channel)

  with open("users.json", "w") as f:
    json.dump(users, f)

async def update_data(users, user):
  if not user.id in users:
    users[user.id] = {}
    users[user.id]["experience"] = 0
    users[user.id]["level"] = 1

async def add_experience(users, user, exprience):
  users[user.id]["experience"] += exprience

async def level_up(users, user, channel):
  experience = users[user.id]["experience"]
  level_start = users[user.id]["level"]
  level_end = int(experience ** (1/4))

  if level_start < level_end:
    await client.send_message(channel, f"{user.mention} Has Leveled Up!  They Have Leveled Up To Level {level_end}!")
    users[user.id]["level"] = level_end

#Commands !level (Gets Level), And !leaderboard (Gets The Top 10 Highest Leveled People In The Server).

#Stop Being Able To Level Up And Get Experience When Doing Commands Or Spamming.

client.run(os.getenv("Token"))
client.run(os.environ["Token"])```
#

But, for some reason the JSON File doesn't update and no message is sent at all.

#

Please help.

fading marlin
#

Member.id returns an int, you can't have an integer as an index in a JSON file, try str(user.id) instead of user.id

slate swan
#

for await ctx.guild.bans() remove the await

potent spear
fading marlin
#

guild.bans() returns an async iterator

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list...
slate swan
steep drift
potent spear
slate swan
#

wait, are the docs you sent v2?

steep drift
fading marlin
#

read the docs that Sniper sent

potent spear
#

you'll have to do some other shit

#

specifically

#

async for ban_entry in ctx.guild.bans():

fading marlin
terse coyote
#

how to make button (discord_components) clickable only for ctx.author?

steep drift
#

It works now, ty dude!

#

By any chance would you know how to loop through a JSON File and get the top 10 highest levels and put it into a command?

potent spear
#

which is NOT its intended use

warped mirage
#

TypeError: eightball.eightball() takes 1 positional argument but 2 were given

#

guys how can i fix this

potent spear
#

we need to see full traceback and your code ofc 🧠

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

potent spear
warped mirage
potent spear
warped mirage
#

Ok works

steep drift
steep drift
#

This is really the only option for me.

potent spear
#

yeah, using a database...

#

it's not

steep drift
potent spear
#

aiosqlite or asyncpg

steep drift
#

how would I switch everything from it.

potent spear
potent spear
# steep drift how would I switch everything from it.

When writing an SQL schema, the important thing to remember is you have a limited number of columns and tables, but unlimited rows.
So, for the following json document design

{
user_id:{
  money:int,
  name:str,
  inventory:
    [
      {
        item\_name:str
        description:str
        count:int
      }
    ]
}
}

we would create three tables:
a user_info table:
user_id INTEGER, name TEXT, money INTEGER\
an item_info table:
item_id INTEGER, name TEXT, description TEXT
and a user_inventory table:
item_id INTEGER, user_id INTEGER, count INTEGER
Further, user_inventory's item_id and user_id would be foreign keys referncing item_info and user_info.
item_id could be set to autoincrement as well.
The schema is avaliable here: https://paste.sr.ht/~vex/84d3be4b80eb7a062651cf2f8acb4046087b9031

But, why? Why would you expand this all to three tables?
Well, a number of things- firstly, we're not creating a bunch of duplicate data- for the above json document, if two users had the same item, we would need to copy the whole item document. In this schema, we just reference an individual row with that data. Further, because of our usage
of foregin keys, if we delete an item from item_info, it propigates to every single user's inventory and is removed- or, if a user is
removed, their inventory entry is cleared as well.

#

To retreive values, we would join the tables on each other. For example, to retreive the inventory of a user with ID 1234, we could do the following query:

SELECT item_info.item_name, 
       user_inventory.count 
FROM   user_inventory 
       INNER JOIN item_info 
            USING(item_id)
WHERE  user_inventory.user_id = 1234 ```
To add an item to a user's inventory using an item name by their ID, we could do the following:
```sql
INSERT INTO user_inventory 
VALUES (1234, 
        (SELECT item_id 
         FROM   item_info 
         WHERE  item_name = "pills"), 
        1) ```
#

=> stolen from discord py help server

steep drift
#

But just the basics right?

potent spear
#

sure, CRUD operations

keen mural
#

if im using await view3.wait() how can i make it wait for 1 second

steep drift
keen mural
#

view3 is a button view

steep drift
steep drift
potent spear
#

SQL is the language databases use

steep drift
steep drift
potent spear
keen mural
#

can u link

potent spear
steep drift
potent spear
keen mural
#

like link the docs

potent spear
#

well, just look for the wait method

#

it might have a kwarg with a timeout or whatever

#

I don't use v2, so can't say

zealous jay
#

How do I create a subcommand in discord.py? Im using slash commands btw

slate swan
terse coyote
#

how to make button (discord_components) clickable only for ctx.author?

slate swan
#

!d discord.ui.View.wait

unkempt canyonBOT
#

await wait()```
Waits until the view has finished interacting.

A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop "discord.ui.View.stop") is called
or it times out.
terse coyote
#

me?

keen mural
#

ok

terse coyote
#

ok

keen mural
slate swan
#

While constructing the view

#

!d discord.ui.View

unkempt canyonBOT
#

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

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

New in version 2.0.
keen mural
#

oh thanks

slate swan
#

Not sure if buttons can be enabled/disabled into discord ui for a particular user

wet crystal
#

!e

unkempt canyonBOT
#
Missing required argument

code

zealous jay
#

This needs to be your bot's token

wet crystal
#

just dont want to leak it

zealous jay
#

oh ok

#

I would recommend using an .env

wet crystal
zealous jay
#

I don't use nextcord so im not able to help, sorry

wet crystal
#

just 4 letters are diffrent

zealous jay
#

huh

wet crystal
cloud dawn
#

Is this a slash command?

wet crystal
#

no there shouldnt be a slash command if u mean that

cloud dawn
#

I'm pretty sure it's a regular command, it should be just ctx.send() not ctx.send_message()

#

send_message is a InteractionResponse.

wet crystal
#

let me change that rq and run again

#

didnt change anything

cloud dawn
#

Please provide the traceback.

wet crystal
#

only the bot.event works

wet crystal
#

it just doesnt work

cloud dawn
#

I recommend just removing the on_message event.

wet crystal
#

litearlly

cloud dawn
wet crystal
#

alright

#

ill give it a shot

cloud dawn
#

If you do want to keep the on_message event put await bot.process_commands(message) at the end of the event.

wet crystal
#

U ARE A WIZARD

#

why is it working this way?

#

i need to understand

cloud dawn
#

Since the Bot extension also is just an on_message you overridden the commands.

#

You can also make on_message a listener to avoid this.

wet crystal
#

@cloud dawn , let me tell you something

#

I love you

#

ur literally the best!

cloud dawn
steep drift
unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

slate swan
#

you can make a custom cooldown for those on_message s

flat solstice
#

Hi So I have this task loop py @loop(minutes=5) async def afk_check(self): print("Afk check loop triggered.") puffcord = self.bot.get_guild(self.bot.config.default_server) log_channel = puffcord.get_channel(self.log_channel) embed = Embed(colour=Colour.dark_orange(), timestamp=datetime.now()) embed.set_author(name="AFK Members") for member in puffcord.afk_channel.members: print(f"{member.name} is in the afk channel.") if member.id not in self.akf_members: self.akf_members[member.id] = datetime.now() print(f"{Member} is not in the afk_members dict, adding them.") if member.id in self.akf_members.keys(): print(f"{Member.name} is in the afk_members dict, checking time.") if (datetime.now() - self.akf_members[member.id]) > timedelta( minutes=self.allowed_time ): print("Passed time comparison") self.count += 1 while len(self.akf_members) >= 1 and len(embed.fields) < 24: print(f"Adding {member} to embed") embed.add_field( name=f"{member.name}#{member.discriminator}", value=f"{member.id}", inline=False, ) del self.akf_members[member.id] which gets to ```py
print(f"Adding {member} to embed")
2022-05-27T22:40:03: Adding SnowyJaguar#1034 to embed

#

actually I think I found the error ```py
2022-05-27T22:40:03: Unhandled exception in internal background task 'afk_check'.
2022-05-27T22:40:03: Traceback (most recent call last):
2022-05-27T22:40:03: File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/init.py", line 101, in _loop
2022-05-27T22:40:03: await self.coro(*args, **kwargs)
2022-05-27T22:40:03: File "/home/testing/cogs/afk_manager.py", line 89, in afk_check
2022-05-27T22:40:03: del self.akf_members[member.id]
2022-05-27T22:40:03: KeyError: 365262543872327681

steep drift
steep drift
cloud dawn
slate swan
cloud dawn
#

Or rather the value.

#

It's a dict right?

flat solstice
# cloud dawn Could you show how `akf_members` is defined?
# In cog init
self.akf_members = {}  # member ID : time
# In voice state event
self.akf_members[member.id] = datetime.now()
# What my logs show when i print the dict
2022-05-27T22:43:55: {791441599997018133: datetime.datetime(2022, 5, 27, 23, 35, 3, 895812)}
```full code: https://paste.pythondiscord.com/adukovuyur
cloud dawn
#

Who is 791441599997018133

flat solstice
# cloud dawn Who is `791441599997018133`

one of my alts, which now I realise wasn't removed from the dict so that makes sense. Now it's odd that it says it added me to the embed twice when it hasn't done it once

heavy shard
#

what's the purpose of the while loop?

#

a haunch says it should be if

flat solstice
#

okay I'll try that

wet crystal
#

for legal reasons this is a joke and not even mine

slate swan
#

But yeah its not very "cool" ik

visual yarrow
#

@wet crystal Don't post code containing such content here in the future please.

plucky flower
#

Can python make a bot like dyno?🙂🙂I am new

visual yarrow
#

I did pithink

slate swan
#

e.g mee6 is made in python which mee6 is one of the most popular bots in discord so i wouldnt underestimate python 😉

crisp bloom
#

pls sho

#

pls shop

slate swan
#

dank memer isnt in this server lol

#

Anyone know if there is any bot who russian roulettes and kicks a random guy from the call?

slate swan
visual yarrow
visual yarrow
slate swan
#

Russian Roulette isnt just having a random one losing instantly but also to have somewhen, where nothing happens, these ate called böanks

#

Hoe could you integrate a 5/6 chance to have a blann

visual yarrow
#

Something like if random.random() < 5/6: ...

#

random.random() is a random number between 0 and 1.

heavy shard
#

or a counter randomly initialised to number from 1 to 6, decreasing every try, and triggering on 0

#

depends on the implementation

pliant gulch
#

You could also use randint(1, 6) anything other than 1 being a blank

glacial echo
#

is there any current build overrides for making slash commadns visually better?

scarlet sorrel
#

can you get an ID from a name, like 944202890015277106 from 𝔃𝓱#1209?

winged bone
#

Not directly

flint isle
#

how can i verify if the user is the bot owner?

winged bone
scarlet sorrel
#

how do you get it from name tho

scarlet sorrel
winged bone
scarlet sorrel
#

the bot will be in the same guild if thats what you mean

winged bone
#

Ah okay

#

This is how you would get the member matching name and discriminator (the number after #)

member = discord.utils.get(guild.members, name="name", discriminator="1234")```
scarlet sorrel
#

jesus

#

wouldn't have worked that out on my own

winged bone
slate swan
#

!d discord.ext.commands.MemberConverter be like

unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
zealous jay
#

Could someone help me creating a subcommand? Im using slash commands with discord.py

heavy folio
zealous jay
#

I have some commands inside a cog

#

Do I send it?

maiden fable
#

They are rare for us people anyways

#

They are mainly made for Discord Devs to test the stuff out without repeatedly updating and degrading their client

jagged adder
#

ive cut this down massively to simplify this, but does anyone know why this isnt firing off when i send a msg? (context in second code box)

if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
            if not ctx.bot.game_states[str(game_channel.id)].begun:
                await game_channel.send("**Act One, Scene One: The Beginning**")
class NewGameState:
    valid_game_options = []

# the game_channel.id part is customised, but i can confirm it works.
ctx.bot.game_states[str(game_channel.id)] = NewGameState()

ctx.bot.game_states[str(game_channel.id)].valid_game_options = ['ready', 'play', 'start']

if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
            if not ctx.bot.game_states[str(game_channel.id)].begun:
                await game_channel.send("**Act One, Scene One: The Beginning**")
                ctx.bot.game_states[str(game_channel.id)].begun = True # Starts the game
sick birch
#

Have you tried printing

print( ctx.bot.game_states[str(game_channel.id)].valid_game_options )
```?
#

That might clue you in as to what's going on

jagged adder
#

i mean i know the valid_game_options is correct because

while ctx.bot.game_states[str(game_channel.id)].game_over:
  await game_channel.send(content=f'When ready to play, type any one of the following: {options_string}')

again simplified, but it prints out the string

sick birch
#

What do you mean by "correct"? What values does it hold?

jagged adder
#

it should be

ctx.bot.game_states[str(game_channel.id)].valid_game_options = ['ready', 'play', 'start']
#

and it prints those 3 options

#

it just doesnt seem to pick up on inputs

sick birch
#

Okay, and you don't reassign any values? It's just a static list?

jagged adder
#

the values can be changed; if i pm u the pastebin link for the entire thing so u got context would that help?

sick birch
#

Yes please, paste the link here though

jagged adder
#

whats the command for pastebin?

#

i dont remember

sick birch
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

jagged adder
#

theres a considerable amount, so i tried to cut down on what was irrelevant to the issues im having rn

#

@sick birch

sick birch
#

Cool, just scanned it. To be clear, the issue is that it won't send the message Act One, Scene One: The Beginning?

jagged adder
#

yes, as everything else comes after that anyways

#

until i can get it to accept inputs in the channel i cant go forward with any other parts of the 'story' code anyways

sick birch
#

Can you try printing ctx.bot.game_states[str(game_channel.id)].begun?

print(ctx.bot.game_states[str(game_channel.id)].begun)
#

So like

if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
  print(ctx.bot.game_states[str(game_channel.id)].begun)
  if not ctx.bot.game_states[str(game_channel.id)].begun:
jagged adder
#

ok

sick birch
#

It can A) not print anything at all or B) print False

jagged adder
#

yeah printed nothin

sick birch
#

In that case, can you try this

print(msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options)
```?
#

If it doesn't print anything again it should be an easy fix

jagged adder
#

where soz?

#
print(msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options)
        if msg.content.lower() in ctx.bot.game_states[str(game_channel.id)].valid_game_options:
            if not ctx.bot.game_states[str(game_channel.id)].begun:

there?

scarlet sorrel
#

what does inline mean in discord.Embed.add_field ?

sick birch
#

Yes

jagged adder
#

yeah still nothin

sick birch
sick birch
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.

scarlet sorrel
#

textbook mistake, even

#

lol

scarlet sorrel
#

kinda useless

jagged adder
#

r u saying its able to read text commands but not plain text inputs ?

sick birch
#

You have intents.message_content=True?

sick birch
flint isle
#

how can i implement a bot owner only command

sick birch
#

It's placed in different spots on discord

scarlet sorrel
flint isle
sick birch
#

Which cannot be accomplished using \n, yes

scarlet sorrel
#

but like 3 pixels at most

sick birch
#

And if it's side by side it's more of a grid layout

scarlet sorrel
#

oh

#

so it makes a grid for you?

jagged adder
scarlet sorrel
#

with columns properly aligned?

sick birch
sick birch
#

Not guaranteed though

slate swan
scarlet sorrel
slate swan
#

on mobile phones, its always inline=False

scarlet sorrel
sick birch
scarlet sorrel
#

no

sick birch
#

The first 2 fields have inline=True passed, the last 2 have inline=False

slate swan
scarlet sorrel
#

there is only 1 set of inline ones

#

if there was 2 sets with different length strings it would show it

sick birch
#

If you set all 4 of them to inline, it'd be in a 2x2 grid layout

jagged adder
#

tbh this is the only line with the word intent

bot = commands.Bot(command_prefix='&', intents=discord.Intents.all())

then its got the perms

perms = {
        ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
        ctx.guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
        ctx.author: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
    }
    game_channel = await category.create_text_channel(f"{str(ctx.author)}'s game", overwrites=perms)
    await game_channel.send(content=f'{ctx.author.mention} your game will be played in this channel.')

where in the code would i have to add your intent msg

plucky flower
slate swan
# scarlet sorrel if there was 2 sets with different length strings it would show it

stop assuming things and making your own theories! this is how i got that output

-v jsk py ```py
embed = disnake.Embed()
embed.add_field(name="inline1", value="value")
embed.add_field(name="inline2", value="value")
embed.add_field(name="not inline1", value="value", inline=False)
embed.add_field(name="not inline2", value="value", inline=False)
await _ctx.send(embed=embed)

sick birch
#

I don't know who says Python isn't good for discord bots

dusky pine
scarlet sorrel
#

gonna have to do some fun stuff to some lists to make that happen

slate swan
plucky flower
#

What language also probot/dyno used?

sick birch
#

Often it's said that discord.js is closer to the API, e.g lower-level. discord.py is a bit more higher-level, sort of like a framework rather than a library, if you will. More features, heavier, that sort of things.

slate swan
sick birch
dusky pine
plucky flower
#

Oo

sick birch
#

Carlbot is definetely discord.py. I talked to the creator a while back on discord.py, cool guy, learned some good stuff from him

slate swan
scarlet sorrel
dusky pine
#

Carlbot is being rewritten in pycord afaik

slate swan
#

even dyno doesnt uses the current state of discord.js
it uses eris which is a djs 8 fork

slate swan
sick birch
scarlet sorrel
slate swan
plucky flower
#

Oh

sick birch
#

If you count your own custom bots, I would argue that's more customizable than any other bot out there, since obviously, you were the one who created it

slate swan
scarlet sorrel
slate swan
slate swan
flint isle
#

how can i make a command botowner only

slate swan
#

!d discord.ext.commands.is_owner

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

😭

scarlet sorrel
#

🤣

dusky pine
#

backward

slate swan
#

i wish this channel was focused more on discord bot discussions than random topics.

dusky pine
#

@scarlet sorrel = literally flake8 for english

slate swan
#

sorry auto correct

scarlet sorrel
#

flakeght?

dusky pine
#

ESLint?

scarlet sorrel
#

wat

dusky pine
#

english linter

scarlet sorrel
#

???

#

tf is linter

dusky pine
#

😐 whatever

slate swan
dusky pine
#

^

scarlet sorrel
flint isle
dusky pine
#

flake8 is a python linter

slate swan
unkempt canyonBOT
dusky pine
#

see kids, jokes can go terribly wrong when someone doesn't understand

sick birch
#

We use flake8 as a pre commit hook for most of our projects here at PyDis, very useful stuff so we can focus on actual code rather than stylistic errors

scarlet sorrel
slate swan
#

is it normal to have a bot which was just created to be ratelimited? :kek:

scarlet sorrel
#

jokes are deprecated in 2022

flint isle
#

XD. Ight I'm goin to bed yall have fun.
may your code be error free

slate swan
#

it never started

scarlet sorrel
slate swan
#

im running it locally as you can see in my activity, and again, it never started

sick birch
#

I mainly work on non-python OSS at pydis (ironic, I know) so we usually use other tools

sick birch
#

our org

scarlet sorrel
#

whos org

slate swan
#

python discord, this server...

sick birch
#

our organization

slate swan
sick birch
#

I refer to it that way because most of our open source projects are under the organization (literally, it's under pydis org in github), and I'm part of it

scarlet sorrel
slate swan
#

its a name, which could be in any language.

scarlet sorrel
#

man i cant keep up

slate swan
slate swan
scarlet sorrel
#

@sick birch you're probably older then me, how do you understand these people lmao

slate swan
#

lol

sick birch
slate swan
#

💀

sick birch
#

Especially with channels like these which tends to attract a lot more beginners, you tend to figure out how to fill in the blanks because when people ask questions here, it doesn't always follow the etiquette (if you can even call it that) for asking good questions

#

I don't blame them either, asking good questions can be difficult