#discord-bots

1 messages Β· Page 1045 of 1

sick birch
#

Yeah, best way to get them it to just jump in

#

If you have the winnerRoleID, just use guild.get_role() instead

zealous jay
#

it's easier to learn if you have a project

empty kernel
#

I'm working to create a welcome bot for when new people join a server. I'm making it for a couple friends (each has their own discord server). On my test server it's easy enough to hard code the general channel's ID, but if the bot is being used on multiple servers/guilds, how do I send the welcome message to the general channel of JUST the server that has that new member?

sick birch
#

Are we assuming that in each server, the general channel is called "#general"?

zealous jay
#

you could make it so people can set the welcome channel

sick birch
#

That requires a bit more setup (a database)

zealous jay
#

yeah

sick birch
#

If you're willing to put that effort in, I can walk you through that as well

#

But you did say you were new, so it's probably best to get your feet wet first before doing anything crazy

empty kernel
#

yep! I've basic loop that works for finding my general channel

    for guild in bot.guilds:
        for channel in guild.channels:
            if channel.name == 'general':
                general_channel = channel.id
                print(f'General Channel ID: {general_channel}')

but right now, this only works because it's only one guild πŸ™‚

pliant gulch
#

Instead of iterating the guilds, you should be doing Member.guild in your on_member_join

#

Then just look for the general channel in Member.guild.text_channels

sick birch
#

You're on the right track, but fyi discord.py has a discord.utils.get() method that does this same thing but in a much easier fashion:

import discord
channel = discord.utils.get(guild.channels, name='general')
empty kernel
#

oh nice! yeah, that's much better. That's also good to know @pliant gulch I can play around with both of those and see how each works

pliant gulch
#

Yea, just combine what me and robin said

#

Then it'll only send in the guild which just had a member join

empty kernel
#

πŸ‘ Much appreciated to ya both!

heavy shard
#

can i start Cog task elsewhere than in __init__() for example in on_ready() ?

cloud dawn
heavy shard
#

because the task checks for new comic strip and posts it to certain guild channel if there's new one

cloud dawn
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before
it has connected to the Websocket, overwrite this coroutine...
cloud dawn
#

I recommend using this

torn sail
#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour.
Note that the `__init__` special method does not allow asynchronous code to run
inside it, thus this is helpful for setting up code that needs to be asynchronous...
heavy shard
#

hmmm

#

thank you

native wedge
#

why do i get this error?

minor totem
#

Try printing response.json()

native wedge
#

yea but the command i use makes it so {username} is a player in the api

minor totem
native wedge
minor totem
#

Add an argument to your view, called username and set self.username = username

minor totem
#

This is what is happening here

minor totem
native wedge
minor totem
#

Instead of having a global variable shared by all people who use your bot at the same time, you now have a username for each person that used your command . Before people couldn't use your command at the same time

minor totem
#

For you, this would be def __init__(self, username):

native wedge
#

def __init__(self, self.username = username):

#

?

minor totem
quaint forum
native wedge
#

i did learn classes but i havent programmed in python in a while

#

oh

minor totem
native wedge
#
def __init__(self, username):
      super().__init__(timeout=None)
      self.username = username```
this is right?
native wedge
#
response =  requests.get(f"https://gdbrowser.com/api/profile/{self.username}")```
minor totem
#

Yup tada

native wedge
#

ok

#

Traceback (most recent call last):
  File "C:\Users\a\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\a\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: Button.__init__() missing 1 required positional argument: 'username'
#

hm

minor totem
#

You are looking at the second traceback, can you copy the one above?

#

Do you see where you need to change? There is a line inside of the command you have forgotten to change

native wedge
#

hm

keen mural
#

if i get an error is there a way to handle it while not being command specific

#

like respond

native wedge
slate swan
#

You can use the <code>on_command_error</code> event to handle errors that occur when a command is executed. You can also use the <code>@bot.command(error=...)</code> decorator to handle errors that occur when a command is executed. The decorator takes a callback that will be called with the context and the error. The event takes a callback that will be called with the context, the error, and the original command (if any). If you want to handle all errors, you can use <code>@bot.event</code> instead of <code>@bot.command</code>.

minor totem
minor totem
keen mural
#
@work.error
async def work_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"**Wait a little bit lmao**",description=f"Try again in `{int(error.retry_after/60)}` minutes.", color=discord.Colour.red())
        await ctx.send(embed=em)

heres an example of an error handler i have now

minor totem
minor totem
torn sail
keen mural
#

ah ok

regal pulsar
#

!d discord.ext.commands.on_message_delete

unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

regal pulsar
#

oh

#

well its on_message_delete tho

keen mural
#
@client.command()
async def item(ctx, item=None):
  if item==None:
    await ctx.reply("You must specify an item")
  con = sqlite3.connect("TEST.db")
  con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
  cur = con.cursor()
  sql_params1 = {
  'userid': ctx.author.id
  }
  result = cur.fetchone()
  if item in ('daily', 'dailybox'):
    cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
    dailybox = result['DailyBox']
    await ctx.reply(f"Number: {dailybox}")
    em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
    await ctx.reply(embed=em)```
This works until the `if item in ('daily', 'dailybox'):` part
#

can anyone help?

#

for example the command would be
,item dailybox

#

no response no error msg

keen mural
loud junco
#

oo lemme check my own code

#

but u already set item = None

slate swan
#

doesn't py have a None and Null?

loud junco
slate swan
#

somehow I thought they were different

keen mural
loud junco
#

u are trying to do with argument or command

slate swan
#

couldn't you just set the default value to something instead of null and then throw an error or stop the code if it's null

loud junco
#

@keen mural

keen mural
#

what

slate swan
#

you literally said they're the same 😭

loud junco
keen mural
#

for example the command would be
,item dailybox

loud junco
slate swan
#

alr

loud junco
keen mural
#

wait brb

loud junco
#

async def item(ctx, *, item=None):
u need a star there

loud junco
keen mural
#

doesnt work still

#

and now just doing ,item gives no response

keen mural
loud junco
#

maybe set item: string @keen mural

#

and make an error handler for missing argument

keen mural
#

name string is not defined

loud junco
#

oops
its str sry

#

@keen mural

keen mural
loud junco
#

item: str

keen mural
#

Β―_(ツ)_/Β―

loud junco
#

and its if blah in [,]

#

not (,)

#

@keen mural u used the wrong bracket

slate swan
#

ppft

keen mural
#

doesnt work still

#

no errors

loud junco
keen mural
#

i have that

slate swan
loud junco
#

just make it arg
dont mess up ur life

slate swan
#

type* not rule

loud junco
#

its still working right?

#

async def item(ctx, *, arg: str):

keen mural
loud junco
#

if arg in ['dailybox' or 'daily']

#

send ur code again

keen mural
#
@client.command()
async def item(ctx, itemname=None):
  if itemname==None:
    await ctx.reply("You must specify an item")
    return
  con = sqlite3.connect("TEST.db")
  con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
  cur = con.cursor()
  sql_params1 = {
  'userid': ctx.author.id
  }
  result = cur.fetchone()
  if itemname in ['daily' or 'dailybox']:
    cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
    dailybox = result['DailyBox']
    em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
    await ctx.reply(embed=em)```
loud junco
#

just make it arg 😭

keen mural
#

why

slate swan
#

when all lowercase argument

keen mural
#

what u send doesnt work

keen mural
loud junco
#

ur using error handler?

#

disable it for awhile and try

#
@client.command()
async def item(ctx, *, arg: str):
  if arg == None: #this wont work make a error handler for this
    await ctx.reply("You must specify an item")
    return
  con = sqlite3.connect("TEST.db")
  con.row_factory = sqlite3.Row # Turns the result rows into dictionary objects
  cur = con.cursor()
  sql_params1 = {
  'userid': ctx.author.id
  }
  result = cur.fetchone()
  if arg in ['daily' or 'dailybox']:
    cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
    dailybox = result['DailyBox']
    em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
    await ctx.reply(embed=em)
#

@keen mural

keen mural
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable

keen mural
#

doesnt work still No error msg

#

wait

loud junco
#

then its this problem

cur.execute("SELECT DailyBox FROM Database WHERE User_Id = :userid", sql_params1)
    dailybox = result['DailyBox']
    em=discord.Embed(title=f"Daily Box", description=f"> `{dailybox}` dailyboxes owned\n> A loot box you get from the daily command, you can't get anything good from this, right?/n/n")
    await ctx.reply(embed=em)
keen mural
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable

loud junco
#

what do u input

keen mural
#

,item daily gives that error

loud junco
#

what is NoneType

keen mural
#

idk

loud junco
#

no idea

slate swan
#

whats wrong with this

#

When using slash commands with auto sync true, when I run my application, it shows warning for the guilds in which it does not have perms to create slash commands. Is there a way to not to raise that warning but get the list of guilds where it does not have perms?

feral lichen
#

bro what

slate swan
#

whats wrong with this?

feral lichen
#

wtf

clever moat
#

LMFAOOO

visual yarrow
#

!ban 833379032728600586 Not acceptable conduct here.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @thorn surge permanently.

slate swan
#

no indentation + he informed mods for slangs

torn sail
#

Wtf

feral lichen
#

ngl that was funny

torn sail
slate swan
#

Try except where?

torn sail
#

Oh if ur auto syncing then I’m not sure

slate swan
#

what if I turn it off? How can I sync commands and supress the warning?

#

πŸ‘€

torn sail
slate swan
#

hmm

upbeat vigil
#

hey, an error gets raised when i run my bot that says Package operation failed.

#

anyone know how to fix this?

slate swan
#

which package failed?

upbeat vigil
#
   and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
  Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
   and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
  Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
  So, because python-template depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.

  at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
      237β”‚             packages = result.packages
      238β”‚         except OverrideNeeded as e:
      239β”‚             return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
      240β”‚         except SolveFailure as e:
    β†’ 241β”‚             raise SolverProblemError(e)
      242β”‚ 
      243β”‚         results = dict(
      244β”‚             depth_first_search(
      245β”‚                 PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
exit status 1```
#

i think the discord one 😭

slate swan
#

Do you have an external requirements. txt?

upbeat vigil
#

i don't

#

would i need to include one?

slate swan
#

nah

#

are you on replit?

upbeat vigil
#

yeah

slate swan
# upbeat vigil yeah

check your .toml and .lock file and check if discord's version is set to 1.7.3

#

You are using correct headers?

upbeat vigil
slate swan
#

headers must include token

upbeat vigil
#

do i set both of them to 1.7.3?

slate swan
#

nah thats not it

#

try to use the shell and dopy pip install discord.py==1.7.3

upbeat vigil
#

alr

slate swan
#

Wait other token work?

upbeat vigil
#

does this look right?

#

im pretty lost LOL sorry

slate swan
upbeat vigil
#

the same thing happened

#

the package operation failed

slate swan
#

IDK probably you cannot use this method or you need some different headers

slate swan
#

idk check if your token is correct. I never used it srry

#

it should work tho

#

well, some more things in the discord documentation doesn't work so probably this is the same case

upbeat vigil
slate swan
#

it takes some time

upbeat vigil
#

oh and it failed

slate swan
#

error message?

#

same?

upbeat vigil
#

  Because no versions of discord match >1.7.3,<2.0.0
   and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
  Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
   and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
  Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
  So, because python-template depends on both aiohttp (^3.8.1) and discord (^1.7.3), version solving failed.

  at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
      237β”‚             packages = result.packages
      238β”‚         except OverrideNeeded as e:
      239β”‚             return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
      240β”‚         except SolveFailure as e:
    β†’ 241β”‚             raise SolverProblemError(e)
      242β”‚ 
      243β”‚         results = dict(
      244β”‚             depth_first_search(
      245β”‚                 PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
/home/runner/valorant-help-bot/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
exit status 1```
slate swan
#

its outdated

#

you can use disnake

upbeat vigil
#

so instead of import discord i js do import disnake

slate swan
#

to implement it in your application, replacepy import discordwithpy import disnake as discord

upbeat vigil
#

i see

#

would i have to change my from discord import ___ lines?

slate swan
#

ye replace every discord from import to disnake

#

then use packager in replit to install disnake

upbeat vigil
#

i just made it from disnake.ext.commands import ____

slate swan
#

ye

upbeat vigil
slate swan
#

dont use pip

#

use packager, pip installs will reset after some time

upbeat vigil
#

how do i do that ?

slate swan
#

go to packager under commands

upbeat vigil
#

yeah

#

packager files right

slate swan
#

ye

#

search disnake

#

._.

upbeat vigil
#

disnake 2.5.1 right

slate swan
upbeat vigil
#

alr

slate swan
#

at least problem solved

#

my friends server got nuked but my bot is in there and have admin any command i can use to give me admin or creat a channel?

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
#

if you need admin, then create a role with admin perms and add it to yourself

slate swan
slate swan
#

im trying to save his server before all his members leave

#
role= await ctx.guild.create_role(name= "admin", perms= disnake.Permissions(administrator= True))

await ctx.author.add_roles(role)```
#

implement it in your program

#

in a command

vocal snow
slate swan
upbeat vigil
#

it still says package operation failed

#

dang

slate swan
slate swan
upbeat vigil
#

alright, ill try that thank u for all the help btw i appreciate it

slate swan
#

\πŸ‘

unkempt canyonBOT
slate swan
#

i gotta download package md

robust fulcrum
#
import os

import discord
from dotenv import load_dotenv
from discord.ext import commands, tasks
from discord.ui import Button

intents = discord.Intents.default()

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')


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


@bot.event
async def on_ready():
   print("bot is resdy")

@bot.command(name="invite")
async def embed(ctx):
    embed = discord.Embed(
        title="Bot Invite Link",
        description="Click on the button below to invite the bot :)",
        color=discord.Color.green())
    button = Button(
        label="invite",
        style=discord.ButtonStyle.link,
        url=
        "https://www.google.com/search?q=discord.py+buttons&oq=&aqs=chrome.1.69i176j35i39i362.-1j1j7&client=ms-android-oppo&sourceid=chrome-mobile&ie=UTF-8"
    )
    view = View()
    view.add_item(button)
    await ctx.send(embed=embed, view=view)

bot.run(TOKEN)

I made this command but when i run there's no error but comamnd not working

#

Pls anyone help me with this

indigo pilot
#

hey so, im not sure if you gotta be rlly expieranced to ask shit so uh yeah. not the best at discord.py but still gonna ask

im making a gate keeper system, and when a person submits a application there answers gets saved to a db (plus the vars of the forum ofc, using forums ui feature)

i need a way to get the id of the user (mongo document id) from later up above in the code where i am making a menu to approve/deny the user from a message it sends. not sure if im just being dumb but i cant think of any way to get the id of the user who created the application as interaction.user just will give me the person who is clicking the menu ofc
again not the most expieranced at discord.py as ive only started a few weeks ago and just started messing around with dropdowns today. so im not sure if im just missing a easy way to do this lol

fading marlin
fading marlin
robust fulcrum
fading marlin
#

does your bot application have them enabled?

indigo pilot
fading marlin
#

you can just send it here :p

flint isle
#

how can i listen in a cog for the bot to be ready?

#

this is what i have currently

import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
def setup(bot):
    bot.add_cog(events(bot))
class events(commands.Cog):
    """Useful Features for Bot Development."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')


@commands.Cog.listener()
async def on_ready(self):
fading marlin
#

you've got your indents messed up

#

and your setup function should go after you define your class

robust fulcrum
flint isle
#

so like

import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style

class events(commands.Cog):
    """Useful Features for Bot Development."""
    def setup(bot):
        bot.add_cog(events(bot))

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')


@commands.Cog.listener()
async def on_ready(self):
fading marlin
# robust fulcrum Ye

toggle it off, wait a bit, and toggle it back on, see if that fixes your issue

indigo pilot
#

so sorry that my code is a mess 😭

fading marlin
indigo pilot
#

so i can grab db data

regal pulsar
#

how are you making them submit info

#

a command?

indigo pilot
#

no

flint isle
regal pulsar
#

k

indigo pilot
#

forum

flint isle
indigo pilot
#

this chat is just all over the place lmao, wish there was threads or something in here auto created

regal pulsar
#
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style

class events(commands.Cog):
    """Useful Features for Bot Development."""
    def setup(bot):
        bot.add_cog(events(bot))

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')


    @commands.Cog.listener()
    async def on_ready(self):
        pass

def setup():
    bot.add_cog(events)
#

or something im on mobile

regal pulsar
#

api?

regal pulsar
#

nothing

#

empty function

#

!d pass

unkempt canyonBOT
#

7.4. The pass statement


pass_stmt ::=  "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation β€” when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

```py
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
indigo pilot
regal pulsar
#

huh

#

the user id of who

indigo pilot
#

the submitter..

regal pulsar
#

ill need to know how you’re accessing data from the forum

flint isle
# regal pulsar ```py import disnake from disnake.ext import commands from colorama import Fore,...

is this laid out wrong?

import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style

class events(commands.Cog):
    """Useful Features for Bot Development."""
    def setup(bot):
        bot.add_cog(events(bot))

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')


    @commands.Cog.listener()
    async def on_ready(self):
        print(Fore.GREEN + 'Connected!' + Fore.WHITE)
        print(Fore.GREEN + 'Bot is ready!' + Fore.WHITE)
        print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
        bot.get_guild(798726719573065749)
        channel = bot.get_channel(798726720181633047)
        await channel.send('Bot Online!')
        embed = disnake.Embed()
        embed.title = f"**Online**"
        embed.description = f"[`{datetime.datetime.now().strftime('%b-%d-%Y`] @ [`%I:%M:%S')}`]\n\n" \
                            f"- Bot account: `{bot.user.name}`\n" \
                            f"- Bot ID: `{bot.user.id}`\n" \
                            f"- Guilds: `{len(bot.guilds):,}`\n" \
                            f"- Users: `{len(list(bot.get_all_members()))}`\n" \
                            f"- Disnake Version: `{disnake.__version__}`\n" \
                            f"- Developer: `whiskeythefox$7339`\n" \
                embed.set_footer(text="Logging System")
        GUILD_ID = 798726719573065749
        CHANNEL_ID = 798726720181633047
        location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
        await location.send(embed=embed)

        pass

def setup():
    bot.add_cog(events)
slate swan
indigo pilot
fading marlin
regal pulsar
#

never used it

#

ill have to check

fading marlin
regal pulsar
#

*forum

fading marlin
#

e

slate swan
#

E

regal pulsar
#

i dont know what he means though

#

does he mean modals ;-;

flint isle
regal pulsar
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
fading marlin
regal pulsar
#

@indigo pilot this?

flint isle
slate swan
#

!discord.Embed.add_field

regal pulsar
#

!d discord.Embed.add_field

unkempt canyonBOT
#

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

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

Damn

regal pulsar
#

;/

#

πŸ«₯

indigo pilot
regal pulsar
#

is it a modal

indigo pilot
#

yeah

regal pulsar
#

someone send a screenshot of what a modal looks like

regal pulsar
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
#

Rehold can u send code

indigo pilot
#

even or that dosnt really matter lol..

  1. just look at the code i sent
  2. the user id is a user id, still there in the code
indigo pilot
sick birch
slate swan
#

Again

indigo pilot
#

.

#

#turnonthreadshere

regal pulsar
#

hmm what about a without inheriting from ui.Modal

#

just instantating

#
import discord
from discord.ext import commands
from discord.ui import Modal, TextInput

@bot.command()
async def test(ctx: commands.Context):
    modal = Modal(name = β€œTest”)
    
#

actually idk

#

never used modals or buttons

#

just select menus

indigo pilot
#

pretty sure wont work like that lol

#

idk

slate swan
#

What's the issue

fading marlin
#

tbf, what they're asking for is kinda basic python subclassing stuff

class A:
  def __init__(self, arg1, arg2, ...):  # you can add as many params as you'd like
    self.arg1 = arg1
    self.arg2 = arg2
    ...

a = A("a", "b", ...)
flint isle
fading marlin
indigo pilot
#

What's the issue
for the 3rd time, ^

slate swan
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.
slate swan
#

Same

flint isle
#

thx

slate swan
fading marlin
indigo pilot
fading marlin
indigo pilot
#

ah okay thanks, ill try that

#

ohh wait yeah true omg how did i not think about that

fading marlin
#

lol

stiff gorge
#

how do i make my bot reply to a specific message ? (command in a cog)

indigo pilot
fading marlin
stiff gorge
#

no i mean if i send hello it shud reply with a message

#

idk how to make this cmnd in a cog

fading marlin
#

oh, are you using slash or prefix commands?

stiff gorge
#

prefix

fading marlin
#

ctx.reply then

#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the
[`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") referenced by this context.

For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send")...
stiff gorge
#

no not tht

indigo pilot
#

are we allowed talking about discord.py here too
Or just questions

indigo pilot
#

just like, gen chatting lol
stuff that aint questions but still related to discord.py

stiff gorge
#
@bot.listen()
async def on_message(message):
    if message.content == "purple":
        msg = 'purple'.format(message)
        await message.add_reaction(':purple_square:')
#

how to make this in a cog

fading marlin
#

oh

#

you should take a look into commands then

#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the
decorator or functional interface.
indigo pilot
indigo pilot
#

just so used to js pepeLauth

indigo pilot
fading marlin
lyric apex
#

How to fix this i am using get_prefix Function

fading marlin
slate swan
fading marlin
#

oh

lyric apex
#

What i am supposed to do there?

fading marlin
#

use bot.command_prefix or ctx.prefix instead ig

slate swan
slate swan
#

whats the point of not defining it in the constructor

fading marlin
#

they're trying to get the bot's prefix...?

slate swan
#

nvm I took it the wrong way, my bad

lyric apex
# slate swan code?
async def get_prefix(bot: commands.Bot, message: discord.Message):
    db = sqlite3.connect('prefix.db')
    cursor = db.cursor()
    cursor.execute(f"SELECT prefix FROM prefix WHERE guild_id = {message.guild.id}")
    result = cursor.fetchone()
    if result is not None:
        return f"{result[0]}"
    else:
        return "-"```
slate swan
#

How do I not raise an error and check that I don't have slash commands permissions in a server?

lyric apex
#

@slate swan is it wrong?

slate swan
maiden fable
#

No, can be anything

lyric apex
slate swan
#

and iirc, you got to do something like

return (result)(bot, message)

or am i done for

lyric apex
flint isle
slate swan
lyric apex
slate swan
slate swan
slate swan
maiden fable
#

It isn't? Hmm okay, never used sqlite so I don't remember the return value

slate swan
lyric apex
#

I want it shows the prefix not returning the prefix that is found though using the commands work fine with it*

slate swan
maiden fable
lyric apex
#

This one

maiden fable
#

Do what ash told

#
await bot.command_prefix(ctx.bot, ctx.message) 
slate swan
#

eh?

maiden fable
#

!d discord.ext.commands.Context.invoked_with is also there

#

Wait wrong one

#

!d discord.ext.commands.Context.prefix

unkempt canyonBOT
#

The prefix that was used to invoke the command. For interaction based contexts,
this is / for slash commands and u200b for context menu commands.

maiden fable
#

This one ^^^

lyric apex
flint isle
#

how can i get my bots pfp

slate swan
unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned.
If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientUser.display_avatar "discord.ClientUser.display_avatar").
flint isle
slate swan
maiden fable
#

Use ctx.prefix

lyric apex
torn sail
#

!d discord.ext.commands.Bot.get_prefix

unkempt canyonBOT
#

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

Retrieves the prefix the bot is listening to
with the message as a context.

Changed in version 2.0: `message` parameter is now positional-only.
lyric apex
#

How do i fix it

torn sail
lyric apex
stiff gorge
#
    @commands.Cog.listener()
    async def on_message(self,message):
      if message.content == "purple":
        message = 'purple'.format(message)
        await self.message.add_reaction('πŸŸͺ')
line 22, in on_message
    await self.message.add_reaction('πŸŸͺ')
AttributeError: 'replys' object has no attribute 'message'
maiden fable
#

reply

stiff gorge
#

?

slate swan
livid hinge
slate swan
stiff gorge
stiff gorge
# slate swan its not in a class
class replys(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
      
    @commands.Cog.listener()
    async def on_message(message):
      if message.content == "purple":
       message = 'purple'.format(message)
       await message.add_reaction('πŸŸͺ')
livid hinge
#

it needs a self parameter, no?

#
class replys(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
      
    @commands.Cog.listener()
    async def on_message(self, message):
      if message.content == "purple":
       await message.add_reaction('πŸŸͺ')```
jade jolt
#

i wonder why he's using format

slate swan
#

it probably wasnt in the same line lmao

jade jolt
#

Β―_(ツ)_/Β―

torn sail
livid hinge
supple thorn
#

Looks weird i doubt that will work

livid hinge
#

then overwriting message with a str

#

if they want to change message they need to use message.edit probably

livid hinge
jade jolt
#

yeah.

livid hinge
#

that's in the doc only, as far as I can see ?

trim barn
#

If I'm trying to create script that would run on a specific day at a specific time, what would be the best way going about that?

I intend to use the Discord API because my script includes using user IDs, running them through the Discord API to create them as discord objects, and delete them through a criteria.

livid hinge
#

but yes thats better than nothing @pliant gulch

slate swan
trim barn
#

For example, on June 1, 2022 at 1 PM, I want x to happen using the Discord API, and then at the same time on July 1, 2022, August 1, 2022 ... forever

pliant gulch
#

But the event does exist, not just in the documentation but in the API as well

heavy folio
#

just curious for hyperlinks, what's the actual way to bold text

  1. [**text**](url)
  2. **[text](url)**
slate swan
#

im sure the first one works, dk about 2nd

slate swan
livid hinge
#

what i was envisioning was something more like ABC I guess

#

something that is part of the runtime contract (maybe on GroupMixin for example)

pliant gulch
#

If I understood you correctly, you can just subclass the client and override _get_state with a custom state class with a new parse_message_delete

class CustomState(ConnectionState):
    def __init__(self, **kwargs: typing.Any):
        super().__init__(**kwargs)

    def parse_message_delete(self, data: dict[str, typing.Any]) -> None:
        self.dispatch("message_delete", data) # add your changes
class Client(Client):
    def __init__(self, token: str) -> None:
        super().__init__(token)

    def _get_state(self, **kwargs: typing.Any) -> CustomState:
        return CustomState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **kwargs)
#

@livid hinge this

honest laurel
nimble plume
#

Huiiiii

stiff gorge
#

this commnd dosent work now and dosent show any error

echo knot
#

Im pretty new to coding bots, does anyone know a vid that can show me how to make a bot add a role to a member after they type something

slate swan
#

then use message.author.add_roles to add role

echo knot
#

k thx

maiden fable
feral lichen
#

why doesnt this work?

#
@bot.event
async def on_message(message):
    if message.content == 'he':
        await message.reply("react with checkmark")
async def on_raw_reaction_add(reaction, user):
    if reaction.emoji == ":white_check_mark:":
        Role = discord.utils.get(user.server.roles, name="Dallas Cowboys")
        await user.add_roles(Role)
feral lichen
livid hinge
formal basin
#

Anyone know how I can timeout someone using a bot

maiden fable
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
supple thorn
#

Not user.server.roles

feral lichen
supple thorn
#

Server is called guild

feral lichen
#

i know just i skidded it

#

still dont work tho :/

supple thorn
#

@feral lichen i just now realized what you want

feral lichen
#

yes

supple thorn
#

I changed it

feral lichen
#

to

supple thorn
#

Also don't just say "doesn't work"

#

Give the error message

feral lichen
#

uh ok

#

theres none

livid hinge
formal basin
granite parcel
#

can we have custom emoji in drop down menu?

supple thorn
livid hinge
#

decorator

feral lichen
#

confusion

#

oh

feral lichen
granite parcel
#

@supple thorntell me

livid hinge
supple thorn
supple thorn
feral lichen
supple thorn
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is
called regardless of the state of the internal message cache.

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

yea like a doc is gonna help that i already looked at

supple thorn
#

@feral lichen there is no user

feral lichen
#

i see

supple thorn
#

It's only payload

supple thorn
feral lichen
#

crazy nothig

#

happened

livid hinge
#

do you need to use emoji.name ?

feral lichen
#

if so no

supple thorn
#

That's why i was confused

granite parcel
#

@supple thorncan we have custom emoji in drop down menu?

supple thorn
#

I thought the on_raw_reaction_add was in the message event

#

Since there was no decorator

feral lichen
#

is there any possible way you could write this? seems like a puzzle :/

livid hinge
#

payload.emoji is a PartialEmoji object tho isnt it

supple thorn
#

It's payload.member.guild.roles

#

That should be the right one

supple thorn
feral lichen
#

i know

livid hinge
#

what is the code you have now

feral lichen
#

i was typing i dont want spoonfeeds just asking lol

supple thorn
#

Yeah show the updated code

tropic burrow
#

so im making a joke command


def get_joke(Theme):
    api = "https://v2.jokeapi.dev/joke/",Theme,"?blacklistFlags=racist"
    r = requests.get(api)
    json_data = r.json()
    if json_data["type"] == "twopart":
        return "\n".join([json_data[x] for x in ["setup","delivery"]])   
    elif json["type"] == "single":
        return json_data["joke"]
                
client.command()
async def joke(ctx, theme):
    joke = get_joke(Theme=theme)
    mbed = discord.Embed(
        title=f"Joke of theme: {theme}",
        description=joke
    )       
    await ctx.channel.send(embed=mbed)

but i get:

No connection adapters were found for "('https://v2.jokeapi.dev/joke/', 'Dark', '?blacklistFlags=racist&type=twopart')"
feral lichen
#
@bot.event
async def on_raw_reaction_add(payload):
    if payload.emoji == ":white_check_mark:":
        Role = discord.utils.get(payload.member.guild.roles, name="Dallas Cowboys")
        await payload.add_roles(Role)
supple thorn
#

It's payload.member

#

For adding the roles

feral lichen
#

ight

livid hinge
#

i think they actually might want name if its a standard emoji

feral lichen
#

i tried already

supple thorn
#

Unicode too

feral lichen
#

it doesnt make a difference

supple thorn
#

\βœ…

livid hinge
#

there is no way in hell payload.emoji is ever gonna be equal to a string 🀣

supple thorn
#

Try this

feral lichen
#

i dd

supple thorn
#

Replace your string with the unicide version of the emoji

feral lichen
#

did* doesnt do anything

supple thorn
#

Try now

feral lichen
#

crazy doesnt work

#

🀦

livid hinge
#

the url .. it did a tuple of the url parts instead

supple thorn
feral lichen
supple thorn
#

@feral lichen are you sure the event is triggering?

tropic burrow
supple thorn
#

Add a print statement to it

#

At the start of the function

feral lichen
#

i did

supple thorn
#

@feral lichen also do you have intents?

feral lichen
#

when u typed it lol

#

yes

#

yea the event is triggering just ion know

supple thorn
feral lichen
#

indeed

livid hinge
supple thorn
#

Can the bot see the message that you're reacting to?

slate swan
#

how may i create an invite to the overall server? (not pointed to a specific channel)

livid hinge
#

you can eithee do an f-string , or do "".join(("http...", Theme, "sfjlffv"))

#

(or use + instead of ,)

tropic burrow
#

i iwll use +

slate swan
#

ah really

#

is that sm new

feral lichen
livid hinge
#

do they actually take you directly to the specific channel they were created for?

slate swan
#

!d discord.RawReactionActionEvent.guild_id

unkempt canyonBOT
slate swan
#

in that case, id like my bot to create an invite when it joins a server, how would i tell it which channel to create it to since idk what channels the server has?

#

You can get the guild using bot.get_guild(payload.guild_id)

supple thorn
#

Or is the member object different in payload

slate swan
#

yes, how would i get it to pick a channel tho lol

feral lichen
#

nvm ill just use wait_for

slate swan
supple thorn
#

!d discord.RawReactionActionEvent.member

unkempt canyonBOT
supple thorn
#

Ask the wise guy

feral lichen
#

i tried idk whats up with it

livid hinge
#

it mentiomed something to do with caching

#

not sure if thats relevant or not

#

"Unlike on_reaction_add(), this is called regardless of the state of the internal message cache." ❔

feral lichen
#

!e `print('bot dumb ong')

unkempt canyonBOT
#

@feral lichen :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     `print('bot dumb ong')
003 |     ^
004 | SyntaxError: invalid syntax
feral lichen
#

!e print('bot dumb ong')

unkempt canyonBOT
#

@feral lichen :white_check_mark: Your eval job has completed with return code 0.

bot dumb ong
livid hinge
#

wouldnt concern me tbh

maiden fable
#

Lol

livid hinge
#

ong [sic] pithink

#

i assume omg πŸ˜„

feral lichen
#

!e



for a in range(0, 10):
  print(f"my iq is {a}")
unkempt canyonBOT
#

@feral lichen :white_check_mark: Your eval job has completed with return code 0.

001 | my iq is 0
002 | my iq is 1
003 | my iq is 2
004 | my iq is 3
005 | my iq is 4
006 | my iq is 5
007 | my iq is 6
008 | my iq is 7
009 | my iq is 8
010 | my iq is 9
maiden fable
#

Bro #bot-commands exists

livid hinge
#

code works now ig

tropic burrow
maiden fable
#

command()

tropic burrow
#

i forgor that

maiden fable
#

Also what's yr dpy version?

tropic burrow
#

but in my code its there

#

2.012 smth

livid hinge
#

wheres json from

maiden fable
#

Wait it's yr code

tropic burrow
#

ye

feral lichen
maiden fable
#

Just saw... u have imported the json module

livid hinge
#

am ong

maiden fable
#

And doing smth like

import json
json["main"]
feral lichen
#

huh

#

with open("w.json" "whatever") as f:

maiden fable
#

Huh?

tropic burrow
feral lichen
livid hinge
#

oh that explains probably

#

what's auto-import .. some IDE thing?

maiden fable
#

Yea

#

IDEs auto import modules as u type their name and press enter

livid hinge
#

i wonder if theres any module that supports indexing

maiden fable
#

!d builtins

unkempt canyonBOT
livid hinge
#

!e

import builtins
print(builtins["open"])```
unkempt canyonBOT
#

@livid hinge :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: 'module' object is not subscriptable
maiden fable
#

Huh weird

livid hinge
#

f

maiden fable
#

I remember doing that before πŸ₯²

livid hinge
#

__builtin__ maybe?

#

or __builtin(s?)__

maiden fable
#

Prolly

livid hinge
#

it acts weird is all i remember

maiden fable
#

!e import builtins

unkempt canyonBOT
#

@maiden fable :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ModuleNotFoundError: No module named '__builtins__'
paper sluice
#

what r you trying to do?

livid hinge
paper sluice
#

that look like py2

livid hinge
#

i think the dict/module weirdness still happens in 3

maiden fable
livid hinge
#

but yeah that writeup is from python 2

paper sluice
#

__builtin__ was renamed to builtins in py3

livid hinge
#

so if __name__ == "__main__" then __builtins__ is the builtins module, but otherwise it's a dict

#

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this [builtins] module or the value of [the builtins] module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

#

definitely braincell-killing

maiden fable
#

Agreed

paper sluice
maiden fable
paper sluice
#

when u import __builtins__ from a diff file, the list is produces is huge AF

stiff gorge
#

how to send a message in a new embed when the main embed gets filled

maiden fable
paper sluice
livid hinge
slate swan
#

what's the best way of getting the bots ping (latency) ?

#

I've seen different ways and I just want to know the best way

#

bot.latency ...

maiden fable
slate swan
#

Yea, sure

#

id prefer a f string though, but this works

livid hinge
#

reminds me of a meme but since we dont post those i'll just chuckle to myself

paper sluice
formal basin
#

What does this error mean

formal basin
paper sluice
formal basin
#

So I replace str with int?

glad cradle
#

have you tried: Read the error

paper sluice
#

.id returns int so i dont think u need to, and the list in ur json is empty so you will get an indexerror

glad cradle
#

you are using the member id str as the index of the list

#

to do this you should use a dictionary that has as key the id of the member (str or int) and as a value the number of warn

#

so you can access the value using the key which would be the member id

formal basin
glad cradle
formal basin
glad cradle
#

anyway I would use a database if I were you

formal basin
#

What shall I call the dict?

glad cradle
#

as you want, warn_member_list?

formal basin
#

Sure I guess

glad cradle
#

example of what your json file should look like

{
	"710570210159099984" : 1
}
formal basin
#

warns = {
"710570210159099984" : 1
}

robust fulcrum
#
@client.command()
@commands.has_permissions(manage_messages = True)
async def status1(ctx):
    await  client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="over FLARELANDS"))

I want that bot send at messages when it change status how can I do that

#

Pls help anyone

robust fulcrum
#

What?

honest laurel
#

You want to send message where?

robust fulcrum
#

I made a command which chane bot status i want that it send a message also

honest laurel
#

Into the same channel, right?

robust fulcrum
#

Ye

honest laurel
#

ctx.send

robust fulcrum
#

But it not worked

honest laurel
#

It does work 🀷

robust fulcrum
#

Means place

honest laurel
#

into your function after you change the presence

robust fulcrum
#

Ok

slate swan
#

I mean, json format structure always contains a root dictionary/array

#

which may contain keys, embedded dictionaries, lists, embedded lists in lists, etc.

honest laurel
slate swan
honest laurel
#

It's either object {} or an array []

slate swan
#

but still json files arent really a good way of storing data, that is changed often

honest laurel
#

That's true, unless it's some sort of config file/static data

#

I would use yaml instead though

slate swan
#

{} only
You also may make the string the user and : how much warns
Let it check if the user exist and add +1 to it everytime

slate swan
honest laurel
#

@formal basin I would recommend you to use a sql database instead, they're widely used in many applications, so it's a good opportunity to learn how to use them

formal basin
stone beacon
slate swan
formal basin
#

Doesn’t work

slate swan
#

wonderful, probably some other error

formal basin
#

A key error

#

With an id

honest laurel
#

It means that there's no such key in dictionary

#

Maybe read how they work first if you're having troubles

formal basin
#

Ohh I understand

slate swan
#
File "main.py", line 165, in verify
    veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)
TypeError: check() takes 1 positional argument but 2 were given```

I believe timeout is the error, is there a fix?
honest laurel
slate swan
honest laurel
#

Also reaction_add event has two parameters - reaction and user

slate swan
honest laurel
#

What it doesn't say?
Look at check function this person has:

def check(react, user):
    return react.message.author == ctx.message.author and ctx.message.channel == react.message.channel
slate swan
#

Im not doing this in a channel

#

im doing it in a DM

honest laurel
#

It doesn't matter

#

It accepts two parameters, not one

slate swan
#

so what am i suppose to do

honest laurel
#

Add second parameter to your check function

#

first would be reaction, second would be user

slate swan
#
reaction, user = await client.wait_for('reaction_add', check=lambda reaction, user: reaction.emoji == 'πŸ‘')
await user.send("πŸ‘ to you too!")```
#

like this

honest laurel
#

Yep

slate swan
#

I still am not getting what I want

#

i want veri to be the emoji

veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```
#

and have a timeout

livid hinge
#

is there a way to get all the ids of users who reacted to a message without fetching?

honest laurel
livid hinge
#

oh ok

slate swan
livid hinge
#

oh let me try that

slate swan
#

@honest laurel Help still

honest laurel
livid hinge
#

what's the flatten do ?

honest laurel
slate swan
#

What do i do

honest laurel
#

What exactly doesn't work?

slate swan
#

I still am not getting what I want

#

i want veri to be the emoji

veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```
#

and have a timeout

unkempt canyonBOT
honest laurel
maiden fable
#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.

The `after` parameter must represent a member
and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only...
maiden fable
#

This, prolly?

#

Nvm, someone already told this

slate swan
#

@honest laurel

honest laurel
slate swan
#
veri = await client.wait_for('reaction_add', check = check, timeout = 30.0)```

I want the value of **veri** to be the emoji.
slate swan
honest laurel
#

And?

#

All reactions are emojis

slate swan
#

I want it to check for all emojis.

honest laurel
#

i don't understand what you want to do πŸ˜…

bitter arrow
#

can someone help me?

stray carbon
#
 @commands.command()
    async def tst(self, ctx, nab: Union[nextcord.Role, str]):
        if nab.type == nextcord.Role:
            await ctx.send('{0} is a role'.format(nab))
        elif nab.type == str:
            await ctx.send('{0} is a string'.format(nab))
        else:
            await ctx.send('error')

idk how to do it, can someone help me

slate swan
stray carbon
maiden fable
#

veri is a tuple of user and reaction objects

slate swan
#

What?

#

how do i install d.py 2.0

hearty glacier
#

git clone the repo

honest laurel
#

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

austere gust
#

Hello

#

I have got a linux vps, I installed everything on it, I uploaded my bot, but nothing works expect on_raw_reaction_add events.

#

There is no errors

#

nothing

slate swan
#

@honest laurel py veri, user = await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == 'πŸ‘', timeout = 30.0)

gives off "cannot assign to await expression"

slate swan
#

cannot assign to await expression

#

thats it, its a red squiggly line

#

Doc

maiden fable
slate swan
#
veri, user = await client.wait_for('reaction_add', check = lambda reaction, user: reaction.emoji == 'πŸ‘', timeout = 30.0)```
maiden fable
#

Error

oak warren
#

Isn’t it wait for reaction

maiden fable
#

Nope

#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"),
if the message is not found in the internal message cache, then this
event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead...
maiden fable
#

And no need to add the on_

oak warren
#

Wrong doc

#

It’s wait for

honest laurel
#

Send full traceback

slate swan
#

it only checks for "πŸ‘"

#

I want it to check for every emoji

oblique adder
#

await message.delete(1)
TypeError: delete() takes 1 positional argument but 2 were given

why ?

honest laurel
#

delete doesn't take any arguments

oblique adder
honest laurel
#

It's a keyword only argument

#

delay=...

oblique adder
maiden fable
#

Yes

oblique adder
#

is it the same as

await asyncio.sleep(1)
await message.sleep()

maiden fable
#

Yes

oblique adder
#

ok thank you

honest laurel
#

If it has a delay task would be created, it's not the same as calling asyncio.sleep and message.delete sequentially

maiden fable
#

Well, the crux is just that. It's gonna wait for a second (sleep) and then delete the message, just the implementation is via a task

honest laurel
oblique adder
#

How do I check if a command is being invoked from another command or event

ctx.invoke

glacial echo
#

is it possible to use a bot to reboot the raspberry pi it’s running on?

#

when the monitor turns off cause the tv it’s on has an auto off thing it makes it impossible to really shut it down quickly and easily

maiden fable
brave forge
#

why after installing the new version discord.py have my events and simple commands stopped working?

stray carbon
#
@commands.command()
    async def heist(self, ctx, role: nextcord.Role = None):
        await ctx.send(f'{ctx.author.mention} will be hosting a heist')
        def check(mes):
            return ctx.author == self.bot.user
        mes = await self.bot.wait_for('message', check=check)
        print(mes.embed[0].title)
        if "is starting a bank robbery" in mes.embeds[0].title:
            no = 0
            async for x in ctx.channel.history(limit=50):
                if no != 1:
                    if x.content.lower().startswith('pls heist'):
                        user = x.mentions[0]
                        no = 1
            await ctx.send(f"{user} is being heisted")
        else:
            return

mes = await self.bot.wait_for('message', check=check)
this waits for 1 message only and returns back if the conditions arent satisfied but i want it to wait for all messages sent until it gets timeout

brave forge
honest laurel
#

I would rewrite it as this:

    @commands.command()
    async def heist(self, ctx, role: nextcord.Role = None):
        await ctx.send(f'{ctx.author.mention} will be hosting a heist')
        def check(mes):
            return ctx.author == self.bot.user
        mes = await self.bot.wait_for('message', check=check)
        print(mes.embed[0].title)
        
        if "is starting a bank robbery" not in mes.embeds[0].title:
            return

        async for x in ctx.channel.history(limit=50):
            if x.content.lower().startswith('pls heist'):
                user = x.mentions[0]
                await ctx.send(f"{user} is being heisted")
                break
honest laurel
stray carbon
#

"break" oh

#

got it

#

thanks

honest laurel
#

Should work the same, less code and it's more readable imo

#

Are you sure your event handler doesn't work at all?

stray carbon
#
@commands.command()
    async def heist(self, ctx, role: nextcord.Role = None):
        await ctx.send(f'{ctx.author.mention} will be hosting a heist')
        def check(mes):
            return ctx.author == self.bot.user
        mes = await self.bot.wait_for('message', check=check)
        print(mes.embeds[0].title)

it didnt print the title

#

wait_for waits for one message only

#

and i was trying to do it for multiple messages

brave forge
#
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content.startswith('Hello') | message.content.startswith('hello') | message.content.startswith('Hi') | message.content.startswith('hi') | message.content.startswith('ΠŸΡ€ΠΈΠ²Π΅Ρ‚') | message.content.startswith('ΠΏΡ€ΠΈΠ²Π΅Ρ‚') | message.content.startswith('ΠΏΡ€ΠΈΠ²') | message.content.startswith('ΠŸΡ€ΠΈΠ²'):
        await message.channel.send(random.choice(["ΠŸΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²","ΠŸΡ€ΠΈΠ²","Hello","hello","Hi","hi","ПОКА!!"]))

@bot.command()
async def hell(ctx):
    await ctx.send("БЕБРА") ```

why in the new version discord.py it doesn't work at all!!?!?!??!!?
heady sluice
#

on_message makes your commands stop working

#

either you do bot.process_commands(message) at the end of on_message or replace @bot.event with @bot.listen()

slate swan
#

i made a command group but the thing is when i use a?chelp
the bot sends the guide for it
but when i use a?chelp heist bot sends the guide of a?chelp and embed of a?chelp heist

#
@client.group()
async def chelp(ctx):
  await ctx.send(embed=chelpEmbed)

@chelp.group()
async def heist(ctx):
  await ctx.send(embed=heistEmbed)

code ^

brave forge
#

@heady sluice

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\ToxicPenguin\Desktop\admin\server.py", line 20, in on_message
    await bot.process_commands(message)
AttributeError: 'Bot' object has no attribute 'process_commands'```
ERROR
heady sluice
#

maybe it's outdated

slate swan
#

use bot.listen

heady sluice
#

then replace @bot.event with @bot.listen() instead

slate swan
#

its easier

inner epoch
#

Is there a way to fetch a users profile pic using his/her/theirs username

brave forge
inner epoch
slate swan
heady sluice
heady sluice
brave forge
#

@slate swan

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.author == bot.user:
        return
    if message.content.startswith('Hello') | message.content.startswith('hello') | message.content.startswith('Hi') | message.content.startswith('hi') | message.content.startswith('ΠŸΡ€ΠΈΠ²Π΅Ρ‚') | message.content.startswith('ΠΏΡ€ΠΈΠ²Π΅Ρ‚') | message.content.startswith('ΠΏΡ€ΠΈΠ²') | message.content.startswith('ΠŸΡ€ΠΈΠ²'):
        await message.channel.send(random.choice(["ΠŸΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²","ΠŸΡ€ΠΈΠ²","Hello","hello","Hi","hi","ПОКА!!"]))


@bot.command()
async def hell(ctx):
    await ctx.send("БЕБРА") ```
after installing d.py 2.0 does not work at all
heady sluice
#

haven't used groups yet

heady sluice
brave forge
#

Hell, it doesn't work with your @bot.listen()!!!!!!!!!!!!!

heady sluice
#

did u try

slate swan
#

py bot.listen('on_message')

brave forge
#

No I haven't tried it I'm just saying

#

...

heady sluice
#

oh I found something in your code samandra

slate swan
#

mhm?

heady sluice
#

you did chelp.group on heist instead of chelp.command

light violet
#

async with aiohttp.ClientSession(headers=self.headers) as session:

      async with session.get(f'https://discord.com/api/v10/guilds/{guild.id}/audit-logs?limit=1&action_type=22', headers=self.headers) as r:
        import json
        
        
        auditlog = await r.json()
#

what is wrong

honest laurel
#

Do your commands work?

heady sluice
#

he should use if message.content.lower().startswith() in ('hello', 'hi')

#

mah what does startswith return

heady sluice
#

bool

slate swan
#

both embeds are sent

glad cradle
heady sluice
#

!d str.startswith

unkempt canyonBOT
#

str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
light violet
#

.

formal basin
heady sluice
#

yeah passed list in startswith

brave forge
#

@slate swan @honest laurel @heady sluice

@bot.listen('on_message')
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content.startswith('Hello'):
        await message.channel.send(random.choice(["ΠŸΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²Π΅Ρ‚","ΠΏΡ€ΠΈΠ²","ΠŸΡ€ΠΈΠ²","Hello","hello","Hi","hi","ПОКА!!"]))```
it doesn 't work !
Π½Π΅ Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚!
light violet
#

ignorance

glad cradle
formal basin
glad cradle
#

as I said the best thing would be to use a database

heady sluice
honest laurel
heady sluice
#

you might need message_content intents

brave forge
slate swan
#
veri, user = await client.wait_for('reaction_add', check = react_check, timeout = 30.0)```


gives off 

File "main.py", line 365, in on_raw_reaction_add
if (payload.member.id == 973196740310237234):
AttributeError: 'NoneType' object has no attribute 'id'```

light violet
#

@heady sluice

async with aiohttp.ClientSession(headers=self.headers) as session:
          
          async with session.get(f'https://discord.com/api/v10/guilds/{guild.id}/audit-logs?limit=1&action_type=22', headers=self.headers) as r:
            import json
            
            
            auditlog = await r.json()```
 how to solve
heady sluice
heady sluice
slate swan
#
veri, user = await client.wait_for('reaction_add', check = react_check, timeout = 30.0)```


gives off 

File "main.py", line 365, in on_raw_reaction_add
if (payload.member.id == 973196740310237234):
AttributeError: 'NoneType' object has no attribute 'id'```

light violet
#

yert ignorance i got no help

heady sluice
slate swan
brave forge
#

@heady sluice do you really know the language or are you just writing bullshit ?

heady sluice
#

Imma ignore you this time

heady sluice
stray carbon
stray carbon
slate swan
#

There's no on_raw_reaction_add event in my code.

heady sluice
#

uh

#

line 365

#

!d discord.RawReactionActionEvent.member seems to be None for you

unkempt canyonBOT
formal basin
glad cradle
heady sluice
glad cradle
formal basin
heady sluice
#

maybe no while loop is needed, wait

glad cradle
#

delete warns =

heady sluice
loud junco
#

is that replit?
just use the auto thing
dont edit thing if you dont know how

heady sluice
#

I was thinking you return False in your check if that time isn't reached yet

stray carbon
glad cradle
#

anyway I ridicule it, you should use a database

formal basin
#
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] += 1

    with open('warns.json', 'w') as f:
         json.dump(warns, f)

def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
    
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)]
    return warns

@slash.slash(name="warn", description="admin only")
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
      channel = client.get_channel(944547350448308244)
      save_warn(ctx, member)
      dm = await client.fetch_user(member.id)
      warns = warns_check(member)
      em=discord.Embed(title="Warning", description=(f"{member.name} has been warned, warning number {warns}", f"by {ctx.author.name} Reason: {reason}"))
      embed=discord.Embed(title="Warning", description=f"warning number {warns}. By {ctx.author.name}\nReason: {reason}.")
      await dm.send(embed=embed)
      await channel.send(embed=em)

@slash.slash(name="warnings", description="admin only")
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
      warns = warns_check(member)
      await ctx.send(f"{member.name} has {warns} warnings.") ```
stray carbon
heady sluice
#
messages = [] 
def check(message):
    if message.channel.id == some_id:
        messages.append(message)
    if time > end_of_time:
        return True
    return False
```smth like what I was thinking
formal basin
# glad cradle anyway I ridicule it, you should use a database
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] += 1

    with open('warns.json', 'w') as f:
         json.dump(warns, f)

def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
    
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)]
    return warns

@slash.slash(name="warn", description="admin only")
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
      channel = client.get_channel(944547350448308244)
      save_warn(ctx, member)
      dm = await client.fetch_user(member.id)
      warns = warns_check(member)
      em=discord.Embed(title="Warning", description=(f"{member.name} has been warned, warning number {warns}", f"by {ctx.author.name} Reason: {reason}"))
      embed=discord.Embed(title="Warning", description=f"warning number {warns}. By {ctx.author.name}\nReason: {reason}.")
      await dm.send(embed=embed)
      await channel.send(embed=em)

@slash.slash(name="warnings", description="admin only")
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
      warns = warns_check(member)
      await ctx.send(f"{member.name} has {warns} warnings.") ```
heady sluice
heady sluice
#

it would be stuck on a wait_for

stray carbon
#

:hmm: