#discord-bots

1 messages · Page 792 of 1

tame nymph
#

aiohttp

#

it's lower-level

#

pure async http wrapper

#

you can connect to ws and handle events yourself

slate swan
#

ok

#

ill check it out

final iron
#

Yeah, just don't add the print statement

#

What

#

Then fetch the channel and send the messages in them

#

Not sure

stuck crater
#

will discord.py still work in the future for a bot that merely sends some messages and uses no commands?

final iron
#

Yes unless Discord makes a change that completely changes their api

echo wasp
#
Ignoring exception in command bal:
Traceback (most recent call last):
  File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/workspace/template-python-flask/discord/discord bot beta cog/cogs/fun.py", line 44, in bal
    bank_amt = users[str(user.id)]["bank"]
KeyError: 'bank'

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

Traceback (most recent call last):
  File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/gitpod/.pyenv/versions/3.8.12/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: KeyError: 'bank'``` code: https://paste.pythondiscord.com/ucaxoginuh.py
echo wasp
#

so where do i get the key from because the wallet was working fine?

#

nvm i forgot it will not just write over it if it is not there

slate swan
#

!e

d = {"akey" : "avalue"}
print(d["bkey"])
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | KeyError: 'bkey'
echo wasp
#

it works now that i removed it

slate swan
#

python3
import random
value = random.randint(1, user_input)
print (value)

#

why is that not working?

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 2, in <module>
003 | NameError: name 'user_input' is not defined
slate swan
#

idk

reef trail
#

define user_input lol

dry kelp
#
Ignoring exception in on_guild_stickers_update
Traceback (most recent call last):
  File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\SDR11\OneDrive\Desktop\SpookyCodes\Tests\test.py", line 134, in on_guild_stickers_update
    await guild.create_sticker(name=st2.name, file=before_sticker, emoji=st2.emoji)
  File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 2206, in create_sticker
    data = await self._state.http.create_guild_sticker(self.id, payload, file, reason)
  File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 335, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0): The browser (or proxy) sent a request that this server could not understand
#
@spooky.event
async def on_guild_stickers_update(guild, before, after):

    async for t in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.sticker_delete):

        remove_sticker = [r for r in before if r not in after]

        for st2 in remove_sticker:
            async with aiohttp.ClientSession() as session:
                async with session.get(st2.url) as response:
                    image_bytes = await response.read()
                    before_sticker = discord.File(BytesIO(image_bytes))

                    if remove_sticker:
                        #await guild.kick(t.user, reason="Anti-Nuke: Deleting Stickers")
                        await guild.create_sticker(name=st2.name, file=before_sticker, emoji=st2.emoji)
slate swan
#

you sent a bad request

#

happens when something in your request is invalid so the apis response is a 400http code

dry kelp
#

how do i fix it?

slate swan
#

you send valid info ig lol

#

im not familiar with making direct requests to the discord api

slate swan
#

How do i make a mute command and a un mute?

gaunt ice
#

hmm

final iron
gaunt ice
#

create a role in ur server called muted and make its permissions so that the person with that role cant send messages

final iron
#

Which would you like?

slate swan
#

Timeout

final iron
gaunt ice
#

ok boss

final iron
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
final iron
#

Boom, simple

gaunt ice
#

...

final iron
#

What

gaunt ice
#

nothin

echo wasp
#

Hello so i made a give command idk if i did it right or not but the amount in my wallet or bank stays the same even after giving money to the other person how do i fix that?


    @commands.command()
    async def give(self, ctx,member:discord.Member, amount = None):
        await self.open_account(ctx.author)
        await self.open_account(member)
        if amount == None:
            await ctx.send("please enter the amount to give!")
        bal = await self.update_bank(ctx.author)
        amount = int(amount)
        if amount>bal[0]:
            await ctx.send("Your not that rich!")
            return
        if amount<0:
            await ctx.send("Amount must be greater than zero!")
            return
        await self.update_bank(ctx.author,-1*amount, "bank")
        await self.update_bank(member,amount, "bank")
        await ctx.send(f"You gave {amount} coins to {member}!!")```
final iron
#

Also, please refactor your code to follow pep8

echo wasp
final iron
#

It should be member: discord.Member

final iron
#

You're missing a space

#

Also, you can do is None instead of == None

#

<@&831776746206265384>

slate swan
#

oh no

#

wrong server

#

sorry

final iron
#

mhm

daring olive
#

!mute 815343303251722281 targeting a user possibly with others

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1643682708:f> (59 minutes and 59 seconds).

gaunt ice
#

oh damm

final iron
#

Yeah I don't know. I do the smart thing and not use json as a database

gaunt ice
#

why do u have 2 deposit cmds

#

while u could just use aliases

#

deposit and dep

echo wasp
gaunt ice
#

@commands.command(aliases = ['dep'])

slate swan
# final iron Then just time them out

Would this work

@commands.command()
@commands.has_permissions(timeout=True)
async def timeout(self, ctx, member: discord.Member):
    await timeout(duration=..., until=..., reason=None)
gaunt ice
#

do u want to set the duration?

final iron
gaunt ice
#

lol

zinc geyser
#

Where can I find the Discord.py Rewrite repo. I looked on github, but I can't find it

gaunt ice
#

idk

final iron
zinc geyser
#

oh, that is the rewrite repo. I thought there was a different one

boreal ravine
#

you want the old d.py?

boreal ravine
glad thicket
#

does anyone know why this happens
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'

boreal ravine
unkempt canyonBOT
boreal ravine
#

use that

glad thicket
#

ok how?

boreal ravine
#

also why do you use PrettyHelp? There is a tutorial on how to make your default help command better

boreal ravine
glad thicket
#
import discord
from discord.ext import commands
import json
from dotenv import load_dotenv
import os
import pretty_help

if os.path.isfile('.env'):
    load_dotenv('.env')
else:
    pass

token = os.environ['token']
# Get configuration.json
with open("configurations.json", "r") as config:
    data = json.load(config)
    prefix = data["prefix"]

bot = commands.Bot(prefix)
# Load cogs
initial_extensions = ["Cogs.Tools","Cogs.Pokemon_TCG","Cogs.Github","Cogs.Fun", "Cogs.Quiz"]

print(initial_extensions)


for extension in initial_extensions:
    try:
        bot.load_extension(extension)
    except Exception as e:
        print(f"Failed to load extension {extension}")

menu = pretty_help.DefaultMenu(page_left="◀", page_right="▶", remove="❌")
bot.help_command = pretty_help.PrettyHelp(menu=menu, no_category="Commands")
#

here @boreal ravine

boreal ravine
#

show the full error

glad thicket
#
Ignoring exception in command help:
Traceback (most recent call last):
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\help.py", line 831, in command_callback
    await self.prepare_help_command(ctx, command)
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\pretty_help\pretty_help.py", line 297, in prepare_help_command
    self.paginator.ending_note = self.get_ending_note()
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\pretty_help\pretty_help.py", line 306, in get_ending_note
    return note.format(ctx=self.context, help=self)
AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'

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

Traceback (most recent call last):
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'
slate swan
glad thicket
#

here @boreal ravine

fervent shoal
#

so i kinda need help with a bot ive been trying to code

boreal ravine
fervent shoal
#

the bots supposed to respond to something, but right now it just keeps spamming the response without the keyword

final iron
boreal ravine
final iron
#

!pypi discord-pretty-help

unkempt canyonBOT
fervent shoal
#

this is the code

#

i am a pretty big beginner

#

so i may be very clueless on some things

final iron
#

Damn people don't even have to subclass their help command anymore

final iron
fervent shoal
#

it just says regexGroup isnt defined

final iron
#

Also, please follow pep8 naming conventions. Variable names should be written in snake_case instead of camelCase

boreal ravine
fervent shoal
#

and wont let the thing go

fervent shoal
final iron
boreal ravine
slate swan
final iron
fervent shoal
#

alr

#

thanks so much

#

new problem

final iron
#

Pretty clear error

fervent shoal
#

i am like very clueless

final iron
#

!e

list_ = ["a"]
print(list_[1])
unkempt canyonBOT
#

@final iron :x: Your eval job has completed with return code 1.

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

See what happens?

fervent shoal
#

yes

#

this fine? orrrrrrrrrr did i mess things up

#

nope does not work

boreal ravine
final iron
#

Check out this website for a proper discord bot tutorial

fervent shoal
#

thank you so much

reef trail
#
    @commands.command(usage="`tp!reason user:id`")
    @permissions.has_permissions(ban_members=True)
    @commands.bot_has_permissions(embed_links=True)
    async def reason(self, ctx, member: MemberID):
        """Shows the reason why someone was banned"""
        cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
        if cmdEnabled:
            await ctx.send(":x: This command has been disabled!")
            return

        try:
            await ctx.send(f"{member} was banned for {await ctx.guild.bans(member)}")
        except:
            await ctx.send(f"{member} was not banned")``` am i doing something wrong here? it says that the user hasnt been banned when they sure as hell have lol
final iron
#

hehe

slate swan
#

.....

reef trail
#

MemberID is a custom class, should have mentioned that

final iron
#

Okay

#

Variable names should be in snake_case instead of camelCase

#

Also, pep8 says a bare exception is a nono and its for a good reason. Remove the try/except block and view the whole error

reef trail
#
        cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
        if cmdEnabled:
            await ctx.send(":x: This command has been disabled!")
            return``` you can completely ignore this
final iron
#

When you make a try/except block you want to catch a specific error

reef trail
#
([Mon]-09:21-PM) [ERROR]: bans() takes 1 positional argument but 2 were given``` ah hah
final iron
#

Thats why you don't use a bare exception block

#

!d discord.Guild.bans

reef trail
#

dead bot

final iron
#

I deleted the message

#

I wanted to see if it would return an error if a bad wasn't found

slate swan
#

How long does it take to end up making a good bot?

reef trail
final iron
reef trail
#

at least in my experience

maiden fable
slate swan
#

welp then lets say about 2 years:/ lol

maiden fable
slate swan
#

heres the thing tbh I can't even get a mute/timeout command up:/

#

and i couldn't even get a broadcast cmd up

maiden fable
#

It's fine, you just need some more knowledge

#

I successfully made a mute command after an year of learning

slate swan
#

I started doing stuff with python 2 years ago

maiden fable
#

I started 1 year ago

slate swan
#

Can you end up helping me make a warn system???? if u have time...

final iron
#

People aren't going to spoonfeed you code

#

That isn't what this server is about

maiden fable
#

Can't help rn anyways, I gotta go to school

#

Would be glad to help after coming back, sorry

slim ibex
#

warn system is relatively simple if you make a minimal one

maiden fable
#

Yups

#

If u don't use database and stuff but use a simple dictionary

slim ibex
#

prolly would want to use a db also to store the number of warns, etc

maiden fable
#

Then it's easy

#

Once u understand the simple logic behind it, it's gonna be easy asf

gaunt ice
#

i hab too

#

):

maiden fable
#

I don't really feel sad, it's totally my choice if I wanna go or not

gaunt ice
#

wha

#

brooo my parents force me to

boreal ravine
#

it's for your own good mate

gaunt ice
#

hmmtrue

maiden fable
#

Not me. I myself told them, I want to go to school and they agreed ¯_(ツ)_/¯

slate swan
gaunt ice
#

):

maiden fable
#

Anyways gtg

gaunt ice
#

cyaa

slate swan
#

bye....

gaunt ice
#

everyone has nitro

#

):

slate swan
#

I got 10 days left:/

final iron
#

Until what?

slate swan
#

my nitro ends

slate swan
#

python3
import random
value = random.randint(1, user_input)
print (value)

#

Why isn't it working?

final iron
slate swan
#

Oh my ok

final iron
#

This has nothing to do with discord bots

slate swan
#

Bruh I forced l different realise

prisma spoke
#

🙂

#

:))

dry kelp
#
    @commands.command(aliases = ['wld'], hidden=True)
    @commands.has_permissions(administrator=True)
    @commands.bot_has_permissions(embed_links=True, manage_messages=True)
    async def whitelisted(self, ctx):

        await ctx.message.delete()

        with open(whitelist_path, "r") as f:
            whitelisted = json.load(f)

        if not str(ctx.guild.id) in whitelisted:
            em = discord.Embed(title="![error](https://cdn.discordapp.com/emojis/929402122074730638.webp?size=128 "error") Whitelisted Error!", description=f"Turn on the antinuke first!", color=discord.Color.red())
            await ctx.reply(embed=em, mention_author=False)
            return

        if not whitelisted[str(ctx.guild.id)]:
            em = discord.Embed(title="![error](https://cdn.discordapp.com/emojis/929402122074730638.webp?size=128 "error") Whitelisted Error!", description=f"Nothing was found for this guild!", color=discord.Color.red())
            await ctx.reply(embed=em, mention_author=False)
            return 

        ls, bots = [], []
        count = 1
        for u in whitelisted[str(ctx.guild.id)]:
            bots.append(f"[<@{(u)}> - {u}]")
            count += 1

        for i in range(0, len(bots), 10):
            ls.append(bots[i: i + 10])

        em_list = []
        for k in ls:
            embed = discord.Embed(title=f"![security](https://cdn.discordapp.com/emojis/907074407808241746.webp?size=128 "security") __TRUSTED MEMBERS__ ![security](https://cdn.discordapp.com/emojis/907074407808241746.webp?size=128 "security")", color=discord.Color.from_rgb(black1, black2, black3))
            embed.description = "\n".join(k)
            em_list.append(embed)
        page = PaginationView(embed_list=em_list)
        await page.start(ctx)
#

why is this part not checking if the list is empty

#
        if not whitelisted[str(ctx.guild.id)]:
            em = discord.Embed(title="![error](https://cdn.discordapp.com/emojis/929402122074730638.webp?size=128 "error") Whitelisted Error!", description=f"Nothing was found for this guild!", color=discord.Color.red())
            await ctx.reply(embed=em, mention_author=False)
            return 
royal oar
#

I know this is a simple question but how would i get my bot to send a message when the input for a command is a letter instead of a number?

dry kelp
#

wym?

#

like a say command?

royal oar
#

Like say i made a guess command between 1 to 10

#

and someone said M

#

How would i make it say like "Cant use letters"

#

when that happends

dry kelp
#

just check if it's a letter and not a int value

quick gust
#

u can just try to len() it, if it gives a TypeError then send the message that u can't use letters

royal oar
#

Ok thank you

pallid mango
#

does anyone have a simple timed mute command for python?

prisma spoke
pallid mango
#

where it at

pallid mango
slate swan
prisma spoke
pallid mango
prisma spoke
#

uh what was the prefix

final iron
pallid mango
#

old way of giving muted

prisma spoke
#

uhh

prisma spoke
final iron
tall dust
#

the command is !d

visual yarrow
#

We don't have a command called rtfm.

slate swan
#

Uhh

pallid mango
#

yes im trying but it just isnt working

final iron
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
pallid mango
#

thats the way

final iron
#

!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/master/api.html#discord.Role "discord.Role")s.

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

Simplifies the whole process

pallid mango
final iron
#

Well in that case

#

You would need to get the guild role

#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
pallid mango
#

this is what i have so far

final iron
#

Lets see

pallid mango
#

one moment

#
@commands.command(help = 'Temporarily mute a member!')
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
    muted_role=discord.utils.get(ctx.guild.roles, name="muted")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    tempmute= int(time[0]) * time_convert[time[-1]]
    await ctx.message.delete()
    await member.add_roles(muted_role)
    embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
    await ctx.send(embed=embed, delete_after=5)
    await asyncio.sleep(tempmute)
    await member.remove_roles(muted_role)
#

but it just says mute command not found

prisma spoke
#

ddid u load the cog?

pallid mango
#

its in main

prisma spoke
#

did u add the cog?

final iron
#

Then you shouldn't be using commands.command()

pallid mango
#

oh shoot

final iron
#

You would be using bot.command()

#

Also

pallid mango
#

in my case client

#

but yes

#

?

final iron
#

Ignore that

slate swan
#

!d discord.Member returns both the name and discrim when you send it as a response

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
pallid mango
#

wait so the command works and it sends the embed but it doesnt actually give the role

final iron
#

Would it not return a discord.Member object

slate swan
prisma spoke
#

?

pallid mango
#

wait wait

#

it gives role, but the time is messed up. itll only give it for a split second

slate swan
prisma spoke
final iron
prisma spoke
#

did u do 1s ?

final iron
#

!d discord.Member.display_name

unkempt canyonBOT
#

property display_name: str```
Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
slate swan
final iron
#

That returns a nickname

prisma spoke
final iron
#

So I'm assuming they want a nickname

unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.User.name "nextcord.User.name")
brisk brook
#

The thing still wont work

final iron
prisma spoke
#

wwhich returns the nickname

final iron
brisk brook
#

My button class can't be added to my cogs

prisma spoke
pallid mango
#

well it doesnt really matter what it looks like to me, i just want the time to work correctly first

prisma spoke
final iron
pallid mango
#
@client.command(help = 'Temporarily mute a member!')
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
    muted_role=discord.utils.get(ctx.guild.roles, name="muted")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    tempmute= int(time[0]) * time_convert[time[-1]]
    await ctx.message.delete()
    await member.add_roles(muted_role)
    embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
    await ctx.send(embed=embed, delete_after=5)
    await asyncio.sleep(tempmute)
    await member.remove_roles(muted_role)
#

okay...

brisk brook
final iron
brisk brook
final iron
#

How?

brisk brook
#

I mean a while ago

#

Coz I thought you knew

#

But it's all goods

final iron
#

I don't want to be rude but I don't remember you

prisma spoke
#

go to off topic channel

final iron
#

He's asking for help

prisma spoke
#

this is a help channel

brisk brook
final iron
brisk brook
#

So what I'm trying to do is add buttons to my cogs

#

How do I do it?

final iron
#

You'll need to be more descriptive

prisma spoke
final iron
#

btw, you don't need to nest classes

brisk brook
#

I see

final iron
#

Your buttons class does not need to be in your cog class

brisk brook
#

How do I import classes to my cogs?

brisk brook
prisma spoke
brisk brook
#

Okay thanks

final iron
prisma spoke
#

anyways any other thing?

brisk brook
#

All goods

prisma spoke
#

Okay

brisk brook
brisk brook
#

Self.class = ClassName()?

prisma spoke
prisma spoke
#

from viewfolder import ConfirmView

brisk brook
#

Yeah?

prisma spoke
#

where confirm view is ur view class

brisk brook
#

I see I see

#

how do i apply it to my cogs tho

prisma spoke
#

import it then use anywhere?

pliant phoenix
#

hi

brisk brook
#

It gives me an error

prisma spoke
#

whats the error

brisk brook
#

It says that the children object has no attribute

#

@prisma spoke

prisma spoke
#

give full error

#

idont know ur code nor full error

brisk brook
#

Yeah bet bet I'll finish my workout firsy

#

Then Ill hop on my comp

pallid mango
#

`Ignoring exception in command mute:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/The-Penthouse-Manager/cogs/Mods.py", line 95, in mute
muted_role=discord.utils.get(ctx.guild.roles, name="muted")
AttributeError: 'Mods' object has no attribute 'guild'

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

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: AttributeError: 'Mods' object has no attribute 'guild'`

#
  @commands.has_permissions(manage_messages=True)
  async def mute(ctx, member: discord.Member,time):
    muted_role=discord.utils.get(ctx.guild.roles, name="muted")
    time_convert = {"s":1, "m":60, "h":3600,"d":86400}
    tempmute= int(time[0]) * time_convert[time[-1]]
    await ctx.message.delete()
    await member.add_roles(muted_role)
    embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
    await ctx.send(embed=embed, delete_after=5)
    await asyncio.sleep(tempmute)
    await member.remove_roles(muted_role)
fervent shoal
#

i have this but it shows that the command snipe doesnt exist

pallid mango
#

this is in Mods.py folder, within cogs folder.

#

keep in mind, all my other commands work..

#

and the command works when i change it to client.command and drop it in main.py

#

any solutions?

pallid mango
fervent shoal
#

no

pallid mango
#

ah

fervent shoal
#

is that why

pallid mango
#

no

fervent shoal
#

oh

pallid mango
#

just wondering, if it was a cog then it should be @commands.event or depending on what u set the cogs class to

clear epoch
#

oyo

fervent shoal
#

so do you know how to fix the issue?

clear epoch
#

nice

prisma spoke
#

@commands.Cog.listener()

prisma spoke
timid wagon
#

There's a capital 'W' in there - Python doesn't do camelCase :P

fervent shoal
#

didnt change anythng

timid wagon
#

It's probably a better idea to use @client.command() decorator for this then

fervent shoal
#

where would i put that

#

im like pretty new to all this

timid wagon
#

Have you specified a prefix for your bot?

#

I'm assuming you have a line defining client - client = commands.Bot(...)

#

Also, you're specifying the event for client and running the bot via bot - the objects are different

fervent shoal
timid wagon
#

They should both be same as your specified instance

timid wagon
fervent shoal
timid wagon
#

What have you specified as bot?

fervent shoal
timid wagon
#

You definitely shouldn't do both at the same time

fervent shoal
#

which would i remove

timid wagon
#

bot and client are different "bots" here, for different purposes

fervent shoal
#

would i change one out for the other?

timid wagon
#

What you've done is that you specified the event for the "client" bot, and you're running the "bot" bot... if that makes sense

fervent shoal
#

yes

#

how would i fix that issue

timid wagon
pine drift
#

hey i have a question in sending DMs

timid wagon
#

And run your "client" bot via client.run(...) instead of bot.run(..)

fervent shoal
#

like so

timid wagon
fervent shoal
#

wouldnt that affect the earlier commands

#

or would i put the ! in front of the command word

timid wagon
#

What you're doing in the on_message event should suffice for the !snipe command

final iron
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

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

It's a subclass of discord.Client

timid wagon
fervent shoal
#

so

#

which would i use and how would i change it accordingly

timid wagon
#

It is always better to use the bot framework, if your bot has multiple commands

fervent shoal
#

which it does

timid wagon
#

You wouldn't need to make an if statement for each command then

#

They will be handled as separate async functions

slate swan
#

Its also easier to make parameter

fervent shoal
#

i have these as well

slate swan
#

These are the commands

timid wagon
#

Then you should definitely continue with the bot instance

#

Specify snipe as a command as well, the same way you did for these functions.

#

And uh, keep the bot object I told you to remove earlier

fervent shoal
#

like so?

slate swan
fervent shoal
fervent shoal
timid wagon
timid wagon
slate swan
slate swan
pallid mango
timid wagon
#

Well, I'll help with the part of converting the event into a normal command mmlol

slate swan
pallid mango
#

?

burnt heath
#

how can i import disnake slash commands? or i dont need to import?

slate swan
timid wagon
burnt heath
burnt heath
prisma spoke
#

its a decorator

timid wagon
#

If it's from a cog, you'd just load them as you do with normal commands

prisma spoke
#

ya

slate swan
timid wagon
#

^

fervent shoal
#

i cant explain very well

#

but ig events are something that happens when a condition is met, command happens when user does something

slate swan
#

So, tell me

#

Should snipe be an event?

fervent shoal
#

a command

slate swan
#

Then?

final iron
#

!d discord.on_message_delete

unkempt canyonBOT
#

discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
timid wagon
#

What your function is currently doing is, is it checking each message the bot can see, and further checking if it contains "!snipe"

fervent shoal
#

so

fervent shoal
#

it can detect the other commands

#

just doesnt recognize snipe as a command

timid wagon
#

Yep

slate swan
fervent shoal
#

yea

#

thats the problem

slate swan
#

Dude, its a command not event

timid wagon
#

Because snipe is under client, not bot

pallid mango
#

no…

timid wagon
#

You have specified two different objects

fervent shoal
#

so i remove that

slate swan
pallid mango
#

it doesn’t recognize it as a command because it is an event…

fervent shoal
#

it should work?

timid wagon
timid wagon
final iron
# fervent shoal just doesnt recognize snipe as a command

It will throw that error because you're using an on_message command system with the bot constructor. What is happening is your on _message uses if statements to check if the code starts with a certain a word therefore discord doesn't recognize it as a valid command

pallid mango
#

yea this?

fervent shoal
#

thats a lot of words

timid wagon
#

Yeah, it's client.event

slate swan
timid wagon
#

Not bot.event. They're using bot.run

fervent shoal
#

it would be appreciated if i could get like a few words and what i need to fix

timid wagon
fervent shoal
pallid mango
#

yes, it needs to be a command not an EVENT

slate swan
fervent shoal
final iron
#

Can we all just calm down and speak 1 at a time?

timid wagon
#

Bruh

pallid mango
#

okay cool

fervent shoal
#

oop a bit got cut off

final iron
#

This isn't helpful or productive

slate swan
timid wagon
# fervent shoal

You're now specifying the command under bot, and running client

pallid mango
#

okay well first of all the client.run is wrong

timid wagon
#

Let's back up a lil

final iron
#

^

fervent shoal
#

bot.run

timid wagon
#

Yes, and

final iron
#

We need to back up.

timid wagon
#

You can't just convert an event into a function with just removing one line

#

You're still checking if the message starts with !snipe

pallid mango
#

okay so first of all, i’d like to ask what’s going on with the client.run

timid wagon
#

They've specified commands under bot, and this one event under client

pallid mango
#

no read at the bottom, it doesn’t have a secret or anything. it just shows TOKEN

final iron
#

Can we just remove the client instance to remove some confusion?

fervent shoal
#

ok

zenith basin
#

who needs help

timid wagon
#

I'm assuming "TOKEN" was specified earier

fervent shoal
#

made it easier for me

pallid mango
timid wagon
#

...?

final iron
#

Uhm

pallid mango
#

LMFAOO

#

wait

timid wagon
#

Variables do work that way.

pallid mango
#

i’m wrong, i’m thinking of a replit secret

fervent shoal
#

do i change the client.run to bot.run

final iron
#

Yes

timid wagon
#

Can we assign one person for the job and make it simpler mmlol

final iron
#

I vote me

timid wagon
#

aight

pallid mango
final iron
#

@fervent shoal let's rewind. Have you checked out the tutorial you were linked?

zenith basin
#

@fervent shoal whats the problem

quick gust
#

i see chaos

onyx viper
# fervent shoal

message.content.startswith, message is an instance of discord.Message

final iron
karmic lintel
#

import json

custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']

async def determine_prefix(client, message):
    guild = message.guild
    #Only allow custom prefixs in guild
    if guild:
        return custom_prefixes.get(guild.id, default_prefixes)
    else:
        return default_prefixes

client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)


@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
    #You'd obviously need to do some error checking here
    #All I'm doing here is if prefixes is not passed then
    
    if client.mentions[0] == True:
      await ctx.send(f'My prefix is {custom_prefixes}')
    #set it to default 
    custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
    await ctx.send("Prefixes set!")```
error - str error in guild
fervent shoal
#

i think i understand

slate swan
# fervent shoal

First of all, you are using two bot constructors (discord.Client and discord.ext.commands.Bot), using Client limits you to using only commands inside on_message event while Bot allows you to use Command, that is why using only a single bot constructor, i.e, Bot is ideal, you can remove the Client constructor

fervent shoal
#

gonna go double chek my work

timid wagon
onyx viper
#

👍

final iron
#

Nah I'm heading out

#

Let ash deal with it

karmic lintel
#

import json

custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']

async def determine_prefix(client, message):
    guild = message.guild
    #Only allow custom prefixs in guild
    if guild:
        return custom_prefixes.get(guild.id, default_prefixes)
    else:
        return default_prefixes

client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)


@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
    #You'd obviously need to do some error checking here
    #All I'm doing here is if prefixes is not passed then
    
    if client.mentions[0] == True:
      await ctx.send(f'My prefix is {custom_prefixes}')
    #set it to default 
    custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
    await ctx.send("Prefixes set!")```
error - str error in guild
pallid mango
#

yea for

karmic lintel
#

help me

karmic lintel
final iron
karmic lintel
#

okay

#

you also beginner i see

pallid mango
#

LMFAO

final iron
#

Sure, 2 times isnt a lot but considering the length it really clogs up chat

onyx viper
onyx viper
#

what are you even trying to do there

final iron
#

^

karmic lintel
#

if someone pings my bot it says my prefix is {prefix}

final iron
#

Pretty sure you're trying to make it says it's prefix when mentioned but don't know what you're doing

#

And I was correct

karmic lintel
#

ye

#

s

pallid mango
#

okay so you need a simple command..

slate swan
#

Or just check the mentioned id with yours bot's id

timid wagon
#

Pretty sure that's only used when specifying the prefix in the commands.Bot instance

#

Atleast I've never used it as a decorator thonk

karmic lintel
pallid mango
#

couldn’t this be way simpler?

#

can’t he just make a response command

#

that includes the prefix

slate swan
timid wagon
#

You can probably just use an on_message event for that

pallid mango
reef trail
#

How can i get an emoji from a message reference? heres my command

    @commands.command(usage="`tp!se emote`", aliases=["stealemote", "se", "steale"])
    @commands.guild_only()
    @commands.cooldown(rate=1, per=4.5, type=commands.BucketType.user)
    @permissions.has_permissions(manage_emojis=True, manage_guild=True)
    @commands.bot_has_permissions(embed_links=True, manage_emojis=True)
    async def steal_emote(self, ctx, emote: discord.PartialEmoji = None):
        """Clones any emote to the current server"""
        cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
        if cmdEnabled:
            await ctx.send(":x: This command has been disabled!")
            return
        if emote is None:
            if ctx.message.reference:
                if ctx.message.reference.emoji:
                    emote = ctx.message.reference.emoji
                    await ctx.guild.create_custom_emoji(
                        name=emote.name,
                        image=await emote.url.read(),
                        reason=f"{ctx.author} used steal_emote",
                    )
                    await ctx.send(f"I successfully cloned {emote.name} to the server!")
        else:      
            await ctx.guild.create_custom_emoji(
                name=emote.name,
                image=await emote.url.read(),
                reason=f"{ctx.author} used steal_emote",
            )
            await ctx.send(f"I successfully cloned {emote.name} to the server!")```
I do get this error of course ```py
CommandInvokeError: Command raised an exception: AttributeError: 'MessageReference' object has no attribute 'emoji'``` so any help would be nice
slate swan
burnt heath
#

so am i supposed to do this in every cog?

timid wagon
#
@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        await message.channel.send("Hello lol, it me.")
    await client.process_commands()```
reef trail
spring flax
#

how does is_on_mobile() work? Does it work no matter the status the user is in?

green bluff
#

doesnt send embed?

karmic lintel
#

import json

custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']

async def determine_prefix(client, message):
    guild = message.guild
    #Only allow custom prefixs in guild
    if guild:
        return custom_prefixes.get(guild.id, default_prefixes)
    else:
        return default_prefixes

client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)


@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
    #You'd obviously need to do some error checking here
    #All I'm doing here is if prefixes is not passed then
    #set it to default 
    custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
    await ctx.send("Prefixes set!")```
error - str object has no attribute guild
burnt heath
timid wagon
#

The user being on mobile is separate from the user's status

burnt heath
#

if u mean that uh its emoji name|emoji id

green bluff
#

why does this not send the embed

spring flax
# timid wagon Yes

And typically there'd be a delay before it updating right like if I check now and close the app and open on mobile and check again with a command it won't change instantly right

reef trail
karmic lintel
slate swan
pallid mango
burnt heath
timid wagon
green bluff
boreal ravine
unkempt canyonBOT
slate swan
green bluff
#

whats that

reef trail
karmic lintel
unkempt canyonBOT
#

@karmic lintel :white_check_mark: Your eval job has completed with return code 0.

2
slate swan
#

#bot-commands

#

👀

boreal ravine
#

scammer

karmic lintel
#

spammer

reef trail
#

lmfao

slate swan
timid wagon
#

Bruh

green bluff
#

ok how do i get one

slate swan
#

Buy it

#

;-;

green bluff
slate swan
green bluff
#

the cogs work tho

karmic lintel
#

ashleyy what leyy? XD

green bluff
#

its just load thats not working

slate swan
boreal ravine
karmic lintel
slate swan
karmic lintel
slate swan
#

!d discord.Message.mentions and use the id attribute and check if that is equal to client.user.id

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

karmic lintel
timid wagon
boreal ravine
timid wagon
#

And stop reposting things, thanks.

slate swan
timid wagon
#

?

karmic lintel
timid wagon
#

I just gave an example, so

karmic lintel
#

are thik h yr

timid wagon
#

Now that I think about it, you can't use bot mention as a command prefix then

slate swan
karmic lintel
#

yes

timid wagon
#

It'll trigger that event :P

karmic lintel
#

see there english letters

timid wagon
#

Let's stick to bot discussion, thanks

karmic lintel
timid wagon
#

It won't trigger the mention or?

karmic lintel
#

ash||leyy|| XD

#

sorry friends

slate swan
unkempt canyonBOT
pliant gulch
#

You may also use commands.when_mentioned_or and pass that to the command_prefix kwarg to your bot's constructor

slate swan
#

Thats what I said before welp

burnt heath
#

can sm1 help? my slash commands are working in some commands but not in some commands

#

like its only working in one file

nimble plume
#

?

#

wdym

desert aspen
#

oh ok so i am installing the package dotenv, for a discord bot project and the thing is dotenv is not installing and is taking wayyyy too long to installl soo how to fix??

burnt heath
#

should i send code here?

timid wagon
nimble plume
slate swan
burnt heath
#

oh

desert aspen
#

like its jus stuck here

pliant gulch
burnt heath
#

in that one file i kicked my bot and then invited it again

nimble plume
timid wagon
slate swan
timid wagon
#

Atleast the one that I know of thonk

karmic lintel
#

my code still shows error - str object has no attribute guild

slate swan
burnt heath
slate swan
timid wagon
slate swan
timid wagon
karmic lintel
burnt heath
timid wagon
#

You mentioned you're using disnake. Why not head over to their support server?

pliant gulch
slate swan
#

@karmic lintel remove the self , that's it.

karmic lintel
slate swan
karmic lintel
slate swan
slate swan
# burnt heath it helped at first ;-;

Try specifying your guild id for testing, you can remove them later; this will instantly register those, re-inviting it would just slow down the slash command registration process

burnt heath
pliant gulch
slate swan
timid wagon
burnt heath
#

ok ty

karmic lintel
slate swan
#

!d os.getenv

unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
slate swan
timid wagon
#

?

#

Oh lol

slate swan
#

Nvm

timid wagon
#

Yeah but the thing is, then all your commands shall be guild only

slate swan
#

Oh oof

timid wagon
#

I'm still adding things to the guide, but that part should help :P

karmic lintel
slate swan
#

creepy 👍

#

||Soulful Sarthak||

#

No

karmic lintel
unkempt canyonBOT
slate swan
#

Yeah

timid wagon
#

new nickname incoming :P

slate swan
#

imagine asking ashy to go in an offtopic channel

timid wagon
slate swan
#

Lmao

karmic lintel
slate swan
#

Huh

#

pithink they are active here so..

karmic lintel
#

she eats my mind all way anyway gtg

slate swan
#

and what's the point of question lol

#

slides out before a war starts

unkempt canyonBOT
#

examples/persistence.py lines 19 to 29

class Persistence(miru.View):
    def __init__(self, app: hikari.GatewayBot) -> None:
        super().__init__(app, timeout=None)  # Setting timeout to None

    @miru.button(label="Button 1", custom_id="my_unique_custom_id_1")
    async def button_one(self, button: miru.Button, interaction: miru.Interaction) -> None:
        await interaction.send_message("You pressed button 1.")

    @miru.button(label="Button 2", custom_id="my_unique_custom_id_2")
    async def button_two(self, button: miru.Button, interaction: miru.Interaction) -> None:
        await interaction.send_message("You pressed button 2.")```
slate swan
#

Seems similar to dpy views lmao

#

Nvm that's supposed to be that way

timid wagon
#

It would've been better if buttons didn't require subclassing at all dead

#

Especially for persistent views

timid wagon
#

Well yeah, you can use lists with discord.ui.Button

light violet
#
@commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        try:
            start = datetime.now().timestamp()
            reason = "banning member(s)"
            logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
            logs = logs[0]
            user = logs.user.id
            user_info = self.client.get_user(user)

            if logs.user.id == 902596056901091378 or logs.user.id == 923091156596842566 or logs.user.id == self.client.user.id or logs.user.id == guild.owner.id:
                return
                async with aiohttp.ClientSession(headers=self.headers) as session:
                        async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
                            took = round((datetime.datetime.now().timestamp() - start), 3)
                            log = await r.text()
                            if r.status in (200, 201, 204):
                                logging.info("Successfully banned %s" % (user))
        except Exception as error:
            logging.error(error)
``` what is the prob in this
timid wagon
burnt heath
#

so um how does this guild_ids command work

pliant gulch
timid wagon
#

Huh

pliant gulch
#

E.g ```py
view = View()
view.add_item(button)

timid wagon
#

goes to read the docs

slate swan
#

yea you can just ```py
view = View()
view.add_item(Button ())

pliant gulch
#

!d discord.ui.View.add_item

unkempt canyonBOT
timid wagon
#

Well, TIL

timid wagon
burnt heath
#

yes

#

to test slash command

timid wagon
#

You will only be able to use them in the specified guild

slate swan
timid wagon
#

And that's the only guild in which they will be registered

burnt heath
#

wait arent u this guy

timid wagon
#

Uh yeah

burnt heath
#

nice

slate swan
#

what do you think by their username and avatarcreepy

timid wagon
burnt heath
#

ye i didnt notice their avatar properly

#

ok so uh theirs nothing about guild_ids there

slate swan
#

Wait a minute

#

See a guild_ids kwarg?

burnt heath
#

ye

timid wagon
burnt heath
#

ok ty i didnt see that

timid wagon
#

Yeah just uh, scroll down from what I linked kappa

spring flax
#
translator= Translator(to_lang="en")
translation = translator.translate("Bonjour")
print(translation)

I can't translate to english? This returns bonjour

light violet
#

why api v9 not working

burnt heath
#

wut this mean

slate swan
burnt heath
#

oh

slate swan
spring flax
#

my bad

slate swan
burnt heath
slate swan
slate swan
burnt heath
#

oh

light violet
#

;

#
 @commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        start = datetime.now().timestamp()
        reason = "Feature Anti-Nuke | Banning Members"
        async with aiohttp.ClientSession(headers=self.headers) as session:
                    
                async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
                            took = round((datetime.datetime.now().timestamp() - start), 3)
                            log = await r.text()
                            if r.status in (200, 201, 204):
                                logging.info("Successfully banned %s" % (user))
                                c = self.bot.get_channel(892973735802449943)
                                await c.send(f"Banned %s, took: {took}" % (user))
                            else:
                                logging.error(f"Could not ban %s" % (user))```


what is the prob in this discord v9 api works or not
nimble plume
burnt heath
#

i tried the guild command, it didnt work ;-;

timid wagon
burnt heath
#

then where '

timid wagon
#

...do you remember specifying bot = commands.Bot(...) at the start of your script?

#

You just add the test_guilds attribute to that instance

burnt heath
#

in that cog?

timid wagon
#

No, in the main file

burnt heath
#

ok

timid wagon
burnt heath
#

um i think im astoundingly dumb but i really cnt find it ;-;

timid wagon
#

Which file do you run to start the bot mmlol

burnt heath
timid wagon
#

What do you see there?

burnt heath
#

i searched there

#

and there is nothing like that at beginning

timid wagon
#

I-

#

Can you share the code or?

burnt heath
#

ok wait

unkempt canyonBOT
#

Hey @burnt heath!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

burnt heath
timid wagon
#

It's right there ;-;

#

Right after all the imports

burnt heath
#

wait u meant that/

timid wagon
#

Anyway, that's where you add test_guilds

burnt heath
#

im dumb

timid wagon
#

I won't judge that, you've just imported Bot directly :P

burnt heath
#

wht?

timid wagon
#

Did it work?

burnt heath
#

i didnt test it yet

#

yes it worked ty

timid wagon
#

Alrighty

crimson tendon
#

hello, I got a simply question about hardware.

I actually run my discord bots on a raspberry pi 4b 2go.
I bought a qnap nas (TS-431k).
Would it be better to run my discord bots on my nas or is it better to transfer them to my nas ?
my nas got a 1.7GHz CPU and the raspberry got a 1.5GHz CPU if I correctly googled it,
my NAS got 1go RAM DDR3 and my raspberry got 2go

pine crown
#

how to sen custom emoji>

native pewter
#

May i know why we use os.getenv instead of directly passing the api key?

tacit storm
#

b: to get it, do

\:whateveremote:

it give you something like this

#

after you get that, just paste it in your message code.

manic wing
#

.env’s are usually on a .gitignore meaning they wont get pushed

tacit storm
#

really?

manic wing
#

most templates i believe

tacit storm
#

ah

brittle flume
#

What is better hikari or discord.py?
In terms of ease to learn

slate swan
maiden fable
slate swan
maiden fable
#

Okay...

keen talon
opaque tiger
#

hello, help needed here, how can we create a private thread in disnake

maiden fable
unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=None, type=None, invitable=None, slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_public_threads "disnake.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_private_threads "disnake.Permissions.create_private_threads") is needed instead.

New in version 2.0.
opaque tiger
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

maiden fable
#

The type kwarg

#

....?

opaque tiger
#

😕

maiden fable
#

I just told you how to

opaque tiger
#

o ok

opaque tiger
#

😄

timid wagon
light violet
#

what is discord's new api

#

someone giveme

timid wagon
#

"new API"?

grand shell
#

is there a way to create a message object without sending the message?

outer flint
#

what kind of permissions did a bot need for joining threads? thinku

quick gust
#

TypeError: Events.on_command() takes 0 positional arguments but 2 were given

#
    @commands.Cog.listener()
    async def on_command(ctx):
        async with aiosqlite.connect("database.db") as db:
            async with db.execute(
                "SELECT user_id FROM blacklist WHERE user_id = ?1", [ctx.author.id]
            ) as blacklisted_fetched:
                try:
                    (await blacklisted_fetched.fetchone())[0]
                    return
                except TypeError:
                    pass```
#

idk if this will even work

rare saddle
#

How to enable sync_permissions for slash commands? | disnake

quick gust
#

oh fuck

spring flax
quick gust
#

right

maiden fable
#

You know...

maiden fable
#

Bro

quick gust
#

yes I got it sarthak

slate swan
#

sorry for triple msg

maiden fable
#

Stop it. Get some help.

quick gust
#

calm down

rare saddle
slate swan
#

my internet lagged

quick gust
#

lmao

maiden fable
#

Rip I know that feeling 👀

spring flax
rare saddle
#

It's

spring flax
#

yes

quick gust
slate swan
#

are you trying to make a check ?

quick gust
#

if the user is botbanned, yes

slate swan
#

!d discord.ext.commands.Bot.add_check use this

unkempt canyonBOT
#

add_check(func, *, call_once=False)```
Adds a global check to the bot.

This is the non-decorator interface to [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") and [`check_once()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check_once "discord.ext.commands.Bot.check_once").
quick gust
#

and I've put it in on_command thinking it will stop executing the code if they are blacklisted

slate swan
#

or override your on_message

quick gust
#

oh lemme see

rare saddle
slate swan
quick gust
spring flax
#

command? Or check

quick gust
#

well the command works, i just need to do the check

slate swan
#

yea thats for description or field values, for title or author you would have to use the url kwarg

spring flax
#

then

@bot.command()
@example()
async def example(ctx):
  pass
quick gust
#

so then I can just add_check to add it globally? or do I have to add the decorator @example in all commands

slate swan
#
async def check(ctx):
   # your stuff

bot.add_check(my_check)
spring flax
#

you can do that too yeah

quick gust
#

ok yes ty lemme try

slate swan
#

that wont be a decorator tho, edited.

spring flax
slate swan
#

but it will force you to use it on each command, a global check would be better as per what they want

spring flax
#

oh i didn't pay attention to that part

#

whoops

quick gust
#
async def blacklist_check(ctx):
    async with aiosqlite.connect("database.db") as db:
        async with db.execute(
            "SELECT user_id FROM blacklist WHERE user_id = ?1", [ctx.author.id]
        ) as blacklisted_fetched:
            try:
                (await blacklisted_fetched.fetchone())[0]
                return False
            except TypeError:
                return True

bot.add_check(blacklist_check)```
Getting CheckFailure 
```py
Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\bot_base.py", line 561, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 922, in invoke
    await self.prepare(ctx)
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\help.py", line 206, in prepare
    await super().prepare(ctx)
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 843, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1152, in can_run
    raise CheckFailure(
disnake.ext.commands.errors.CheckFailure: The global check functions for command help failed.```
#

i most likely did something wrong in the check itself

rare saddle
#

Please tell me if I specified sync_permissions correctly? | An error like this occurs

spring flax
quick gust
#

not my main bot and im too lazy lol

spring flax
#

what's difficult about it?

#

it's just one line

slate swan
#

!format

unkempt canyonBOT
#

String Formatting Mini-Language
The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format().

Take a look at some of these examples!

>>> my_num = 2134234523
>>> print(f"{my_num:,}")
2,134,234,523

>>> my_smaller_num = -30.0532234
>>> print(f"{my_smaller_num:=09.2f}")
-00030.05

>>> my_str = "Center me!"
>>> print(f"{my_str:-^20}")
-----Center me!-----

>>> repr_str = "Spam \t Ham"
>>> print(f"{repr_str!r}")
'Spam \t Ham'

Full Specification & Resources
String Formatting Mini Language Specification
pyformat.info

quick gust
#

true, but I'm not really trying to make this good or anything, this is just a test bot I'm using to try stuff so I cba

slate swan
#
@bot.command()
async def parrot(ctx,num:int,*text):
        try:
            num = int(num)
        except:
            num = 1
        message = " ".join(text)
        await ctx.send(str(message))* num

```  i am trying to send the argument num time but they tell me that * operation is not supported between Message and int
spring flax
#

just do this

bot = commands.Bot(...)
bot.db = bot.loop.run_until_complete(aiosqlite.connect("[datbaase name].db"))```
slate swan
#

is it?

quick gust
#

yes

spring flax
#

CheckFailure is raised when the check fails

quick gust
#

oh so

#

oh lmao, there we go

slate swan
spring flax
#

handle the exception

quick gust
#

yes ill just do that

spring flax
slate swan
#

because the argument can sometimes be null

spring flax
#

can you explain what you want to do?

slate swan
#

or nothing

slate swan
#

it is *args

#

and you cant multiply ctx.send with a number

#

thats not how args for the command constructor work..

#

i want to send the message *num

#

what i should do

#

?

#
for i in range(times):
   await ctx.send(...```
#

what a clever idea

quick gust
#

Thank you Diabolical and Sarthak!

slate swan
#

yw

#

if you want to, nothing is stopping you

#

though whats the point of using it for every command?

#

nah i meant for all commands, even for normal commands everyone can use?

#

it worked thks @slate swan

slate swan
#

yep

#

if you want to check it for bot, use bot_has_permissions

#

yea if you want to

#

wdym

#

use the decorator and the MissingPermissions exception in the error handler

spring flax
#

traceback scrapping?

#

you mean for like a help command it says the perms required for another command?

slate swan
#

!d discord.ext.commands.Command.checks this may be helpful in determining what checks and perms were used

unkempt canyonBOT
spring flax
#

what?

#

you mean you tried that for a discord bot?

#

you would have to use this

slate swan
#

and?

spring flax
#

!d discord.ext.commands.Bot.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.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
spring flax
#

Sure

#

The error kind of explains everything

unkempt canyonBOT
slate swan
#

Exceptions dont have a code attr iirc

#

cof cof read the error

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

!paste @slate swan use this to paste your code

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
#

error.missing_permissions

rare saddle
#

Please tell me if I specified sync_permissions correctly? | An error like this occurs

slate swan
#

didnt you want to change sync_commands

#

first, compare if ex is in instance of commands.MissingPermissions

rare saddle
slate swan
#

remove sync_permissions=False

#

also, its not an error, its a warning

rare saddle
slate swan
#

why do you want to add it?

#

it means the error is happening due to some hierarchy issue, are you doing some mod actions in the command?

rare saddle
slate swan
#

do you know what it does?

rare saddle
slate swan
#

did you add py @bot_has_permission(add_reaction=True) ?

rare saddle
slate swan
#

on the top of command

slate swan
#

ofcourse, thats how the error handler works

#

it first checks if your bot has the permissions or not, if it dont
the MissingPermissions error is raised

rare saddle