#discord-bots

1 messages · Page 838 of 1

pliant gulch
#

A tab and a space are different, that's why python errrors when you mix the two

#

You seem to be confusing the misconception as your IDE does all this for you

slate swan
#

just confused as some editors just convert tabs as spaces

pliant gulch
#

Yea, but that doesn't mean tabs == spaces

slate swan
#

yeah

dull terrace
#

if you accidentally used tabs in a bunch of code that uses spaces couldn't you fix it in like 5 seconds with search and replace all

pliant gulch
#

Depends on your IDE, probably

cold sonnet
pliant gulch
#

I'm sure some searches would return spaces for tabs

slate swan
#

probably

pliant gulch
cold sonnet
#

yeah Ik

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

001 | False
002 | False
final iron
#

Does black turn tabs in to spaces?

slate swan
#

lol

slate swan
#

why would it?

pliant gulch
#

Black turns tabs into spaces iirc

#

There exists a seperate package for black with tabs

pliant gulch
cold sonnet
#

wth

slate swan
#

need helper role i think

cold sonnet
#

!e

class Tabs:
    def __init__(self):
        self.point_in_vsc = "Indents"

class Spaces(Tabs):
    def __init__(self):
        self.point_in_vsc = "Indents"

print(Tabs.point_in_vsc == Spaces.point_in_vsc)
unkempt canyonBOT
#

@cold sonnet :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 9, in <module>
003 | AttributeError: type object 'Tabs' has no attribute 'point_in_vsc'
final iron
slate swan
#

oh it’s just general

final iron
# cold sonnet I suck at this

!e

class Tabs:
    def __init__(self):
        self.point_in_vsc = "Indents"
class Spaces(Tabs):
    def __init__(self):
        self.point_in_vsc = "Indents"
print(Tabs().point_in_vsc == Spaces().point_in_vsc)
unkempt canyonBOT
#

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

True
cold sonnet
#

👍🏿

manic wing
#

!e
x = 3
if x == 3:
print('.')
if x == 3:
print('..')

slim ibex
unkempt canyonBOT
#

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

001 | .
002 | ..
final iron
slim ibex
dull terrace
#

what are the rules for splitting code into seperate modules? The first project i completed ended up being one file of around 2500 lines

manic wing
#

there are no rules per se

slim ibex
#

^

manic wing
#

just try and categorize your commands

#

so help commands can automate them

#

its in your best interest

slim ibex
#

I generally put everything in srcfolder, and split everything up

#

one folder for utils, helpers, etc

manic wing
#

you choose where the line is, its all personal preferance really

dull terrace
#

i mean more in general for python

slim ibex
#

but if you want to show something is a module or lib prolly put an empty __init__.py in there

manic wing
slim ibex
#

you can also use __all__ in __init__.py files (or any file, it is just generally used in __init__.py) to control wild card imports

#

!star-imports

unkempt canyonBOT
#

Star / Wildcard imports

Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.

Example:

>>> from math import *
>>> sin(pi / 2)
1.0

This is discouraged, for various reasons:

Example:

>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2)  # uses sin from math rather than your custom sin

• Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
• Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
• Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.

How should you import?

• Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)

>>> import math
>>> math.sin(math.pi / 2)

• Explicitly import certain names from the module

>>> from math import sin, pi
>>> sin(pi / 2)

Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]

[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python

royal meteor
#

Can somebody send me an invite link for the discord.py official server?

dull terrace
serene mantle
#

Hey guys, im coding my discord bot right now, and for some reason i just got this error
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.setup' raised an error: RecursionError: maximum recursion depth exceeded

manic wing
pliant gulch
frigid pendant
#

how do i get a user by id then private dm them?

serene mantle
#

its never happened before, and it happens on a specfic cog

#
from traceback import print_exception
import random
import requests
import json
import disnake
from disnake import Embed
from disnake.ext import commands 
from pycoingecko import CoinGeckoAPI
from dataclasses import dataclass
from ssl import Purpose
from etherscan import Etherscan
from yaml import safe_load
import time
import asyncio
from typing import Optional
from sqlitedict import SqliteDict
from modules.database import Server

with open('config.yml') as f: config: dict = safe_load(f)

class setup(commands.Cog):
    def __init__(self, client):
        self.client = client

    print(1)

def setup(client):
    client.add_cog(setup(client))```
slim ibex
#

!d discord.DMChannel

unkempt canyonBOT
#

class discord.DMChannel```
Represents a Discord direct message channel.

x == y Checks if two channels are equal.

x != y Checks if two channels are not equal.

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
frigid pendant
#

kk how would i get the user by discord id?

manic wing
#

get_user

dull terrace
slim ibex
#

lol 🗿

dull terrace
#

biggest function is draw_img and it links to maths stuff to randomly generate tiles in specific ways and then there's stuff that actually draws various tiles on conditions

serene mantle
#

@slim ibex @manic wing you guys know a solution for
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.setup' raised an error: RecursionError: maximum recursion depth exceeded

manic wing
#

dont ping random people

manic wing
pliant gulch
#

Recursion 👁️ 👁️ , are you like trying to load your extension inside of setup

#

That would just be a loop^

slim ibex
#

^

#

How the fuck are you surpassing the recursion depth

manic wing
#

your bot calls the setup function

#

so its trying to call both and its having a seizure

#
  • just name errors
slim ibex
#

lmao

frigid pendant
#

member = message.guild.get_member(first_word)

i get this error: ```
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/BaconHubAutoPurchaseHandler/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 28, in on_message
if user:
NameError: name 'user' is not defined

slim ibex
#

is user a param in the function

#

or member

frigid pendant
#

the first_word var is the uers's id

slim ibex
#

show the whole function

frigid pendant
#
@client.event
async def on_message(message):
  print(message.channel.id)
  if message.channel.id == 943253794819555368:
    first_word = message.content.split()[0]

    member = message.guild.get_member(first_word)
    print(member)
    if user:
      print("lolll")
slim ibex
#

user is no where in here

#

Of Course it wouldn’t work

frigid pendant
#

the user is message.author

slim ibex
#

used is not defined as a variable or anything

dull terrace
#

what are you trying to do

frigid pendant
#

get user by id

dull terrace
#

for what purpose?

frigid pendant
#

a whitelist automation im making

dull terrace
frigid pendant
#

oioh shit wait i think i just fixed it

slim ibex
#

prolly shouldn’t do it in an on message event only?

serene mantle
frigid pendant
#

its cuz another bot is sending messages to a private channel for this bot to read

#

so that capicalizatins always the same

serene mantle
frigid pendant
#

nvm

#

see, the first print prints out the id but the get user by id part returns none

#
@client.event
async def on_message(message):
  print(message.channel.id)
  if message.channel.id == 943253794819555368:
    first_word = message.content.split()[0]

    member = message.guild.get_member(first_word)
    print(member)
#

new code

slim ibex
#

you are getting the member from the message content??

frigid pendant
#

yes

#

trust me, im not insane

#

i have a reason for this

slim ibex
#

don’t think this is the most efficient way to do what you want

frigid pendant
#

trust me like i said, itll work out

#

cuz im using a bot i didnt make to send the messages so i cant modify the other bot

slim ibex
#

are you wanting to get the message author or just a random user

frigid pendant
#

s o i have a tebex webstore that sends the user id to a channel and cuz its not my bot i cant modify is so its sending the user id of the person that purchased the product then im having my bot read the message

#

and the first_word variable is the purchasers user id

dull terrace
#

wouldn't your bot not be able to fetch them because it's not in the same guild?

frigid pendant
#

it is in the same guild

#

i added them both to the same guild

dull terrace
#

no, the user you're fetching

slim ibex
#

but like you are trying to get a member with message.content

frigid pendant
#

they are in the guild

#

they are the owner of the guild

#

im trying to get a member by id but the id is a variable

#

that i called first_word

dull terrace
#

only thing i can think of is that you're missing member intents, you could try fetch user

#

await client.fetch_user(id)

frigid pendant
#

and im not ab to loop through all members to check if their user id matches cuz thatll lag too much

#

that worked

#

thx, i finally figured it out

#

yall helped me

dull terrace
#

yeah it was probably members intent you were missing, np

slim ibex
#

np

dull terrace
#

this is the current bot im working on

#

if you need to identify the type of file before sending it then you'd probably need to use twitter api

#

another way i could see doing it, is posting the link which discord will auto embed, then you can get the content of that message which should have the extension

#

possibly

obsidian marsh
#

hey can anyone help me to make stop command?

#
@client.command()
@commands.has_permissions(administrator=True)
async def dmSpam(ctx, user_id=None, *, args=None):
    if ctx.message.author.id == 404354878035722240:
        await ctx.send("spierdalaj")
    else:

        if user_id != None and args != None:
            try:
                while True:
                    target = await client.fetch_user(user_id)
                    await target.send(args)
                    await ctx.channel.send("'" + args + "' wyslano do: " + target.name)
            except:
                await ctx.channel.send("Nie mozna wyslac wiadomosci")

dull terrace
#

wait no that wouldn't work

#

im thinking of uploads

#

probably the best way

manic wing
dull terrace
manic wing
#

but very confusing

rare saddle
#

What method can be used to remove a server role using a bot?

dull terrace
obsidian marsh
dull terrace
#

i've been trying to keep it to 3 lines but

manic wing
#

to much information to process

#

try and make it more visually appealing and easy to use maybe

dull terrace
manic wing
#

it flicks between so many different pages

dull terrace
#

seems like less than a regular game, just energy and depth for gui and then interactions

#

I could possibly move some stuff to later levels to slow the learning curve, like at the start i made it so you spawn with an extra energy thing which makes the use item bar appear

#

but if you have no items then it doesn't show up, so i could move that later as a guaranteed item after you've dug a certain depth for example

cerulean olive
#

🎉

slate swan
#
  1. rate limits
  2. ctx gets the channel were the context was invoke so no need for the channel attr
  3. f strings are a thing
    4.youre making request in a loop which will raise a 429 by the api since youve been making so much api calls in a short amount of time
dull terrace
cedar stream
dull terrace
#

stop replying to me, it's not my code 😤

slate swan
cedar stream
cerulean olive
slate swan
#

?

dull terrace
#

limit=None this should not be None

slate swan
#

add a default value of 1 to limit

#

so it will never raise such an error

#

if you want but i recommend to make it 1 so you will always know the value of it.

#

code?

#

and why add a value to limit when you can add a defualt value in params?

cedar stream
#

limit=1

#

In params

slate swan
#

and it wont work as you set a value to limit in the params of the method you should do it in the methods parameters

#
def method(limit: int = 1) -> None:
    ...
#

here limit is expected to be an int and has a default value of 1 which the method returns None

halcyon sparrow
#

Is anyone else feeling stuck with their bots?

slate swan
#

why?

slate swan
halcyon sparrow
#

I know how to but I just feel sort of down about it

slate swan
dull terrace
fervent shard
#

how can i make it so that if a member goes offline a role will be given to them and when theyre online it will be removed?

halcyon sparrow
#

I've gotten mine up but it doesn't have any commands yet. I have like empty cogs already too. I just feel unmotivated, I guess

slate swan
cedar stream
dull terrace
#

gotta push through the pointless feeling

cedar stream
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

dull terrace
#

everythin pointless

cedar stream
dull terrace
#

the pointless feeling always appears for me about half way through a project and by the time im at 3/4 excited comes back

rocky trench
#

on_member_update(member, before, after)

kindred epoch
#

its just before and after

rocky trench
rocky trench
halcyon sparrow
#

You're right. I gotta push through. Thanks guys. Am gonna start up my terminal

rocky trench
#

Isn't it?

cedar stream
#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change:

• nickname

• roles

• pending...
dull terrace
#

you can do it cloud

slate swan
kindred epoch
cedar stream
cedar stream
#

Just b4 and after

rocky trench
#

Yh i see it now. Don't have my code with me atm

cedar stream
#

Me neither

slate swan
#

weird how it doesnt take that param

dull terrace
#

member param would be same as after

rocky trench
#

Yh indeed

slate swan
#

after and before are member objs yes

rocky trench
#

I wasn't thinking, should've thought more

cedar stream
cedar stream
slate swan
#

you cant learn everything lol

rocky trench
cedar stream
dull terrace
#
async def on_message(message):
  if message.author.id == 897789854472106004 and message.content == "on_member_update(member, before, after)":
    for user in the_whole_of_discord:
      await message.send(f"{user.name}: you wrong")```
slate swan
#

a bot can't cache all users in the api

dull terrace
#

😤 it can sure try

slate swan
#

youll need more than 2tb of ram

cedar stream
dull terrace
cedar stream
#

Caching entire discord db

slate swan
dull terrace
slate swan
#

is there an event that checks the user's presence

#

like on_member_presence stuff like ths

#

why would theyre be an event

#

actually i just forgot the event

slate swan
#

!d discord.Member.status

unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
slate swan
#

idk check docs

pliant gulch
#

In versions less than v2.0 it is on_member_update, you can check the presences to see if they updated

#

And in versions v2.0+ they have on_presence_update

slate swan
#

on_member_update allows me to check the user's bio aka status

#

like if they put something in their status they'll get something

#

whatever

#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change:

• nickname

• roles

• pending...
dull terrace
#
  if after.member.status == something idk what:
    they online```
#

or is it just after.status idk

#

i think it's just after.status

hoary cargo
#

what exactly you want to check

native wedge
#

hello i make talking ben dog

ben_responses = ["yes", "no", "ben", "haha", "eugh"]

@bot.command(name="ask")
async def ask(ctx: commands.Context):
    await ctx.send(random.choice(ben_responses))

why is it repeating more and more responses?

slate swan
#

after and before return member objs?

pliant gulch
#

This does not look right,

dull terrace
#

look im very tired

pliant gulch
#

The docs only show you the parameters it takes. You need to decorate a function with the event or listen() decorator with the event name

#

that being on_member_update

slate swan
native wedge
dull terrace
#

async def on_member_update(before, after):
if after.status == "online":
they online

slate swan
#

that wouldnt work?

#

and he's checking custom statuses

slate swan
analog barn
#

(please)

pliant gulch
#

!d discord.CustomActivity

unkempt canyonBOT
#

class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.

x == y Checks if two activities are equal.

x != y Checks if two activities are not equal.

hash(x) Returns the activity’s hash.

str(x) Returns the custom status text.

New in version 1.3.
pliant gulch
#

!d discord.Member.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
dull terrace
#

is there a consistent font for discord across all devices?

rare saddle
#

How to call a command from another file?

slate swan
rare saddle
slate swan
dull terrace
#

I'm trying to think of a non-dumb way to do this. It generates a certain amount of dashes and spaces after whatever text to make each dashed line end at the same place.

character_size = {
    "lij|' ": -13,
    "![]fI.,:;/\\t": 0,
    '`-(){}r"': 10,
    "*^zcsJkvxy": 35,
    "aebdhnopqug#$L+<>=?_~FZT": 45,
    "SBPEAKVXY&UwNRCHD": 62,
    "QGOMm%W@": 85,
}

def get_dashes(st):
    size, dashes = 0, ""
    for s in st:
        for chs in character_size:
            if s in chs:
                size += character_size[chs]
                break
        size += 50
    while size < 2000:
        dashes += "-"
        size += 60
        if size < 2000:
            dashes += " "
            size += 37
    return dashes```
tidal hawk
#

What does it Rate limit?

rare saddle
tidal hawk
#

For some reason Discord doesn't register my Slash commands globally, it worked locally, it doesn't even let me sync_commands_debug, does somebody know what the problem might be?

slate swan
dull terrace
#

😤

unkempt canyonBOT
#

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

lol_______lol
slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
slate swan
#

which youll need to make a global setup

tidal hawk
#

my slash commands won't go through, can somebody guess the reason

slate swan
#

its all in the tutorial

tidal hawk
#

The slash commands worked locally, but as soon as I made them global, they wont show on the server

rare saddle
kindred epoch
#

it takes 1 hour to load all of them in all servers

tidal hawk
#

It's been 2 hours

slate swan
kindred epoch
#

does the bot have applications.command parameter while you invited it?

slate swan
rare saddle
tidal hawk
slate swan
tidal hawk
#

I'll check!

rare saddle
tidal hawk
#

What does To upser: Slash commands mean though?

slate swan
dull terrace
#

!e

character_size = {
    "lij|' ": -13,
    "![]fI.,:;/\\t": 0,
    '`-(){}r"': 10,
    "*^zcsJkvxy": 35,
    "aebdhnopqug#$L+<>=?_~FZT": 45,
    "SBPEAKVXY&UwNRCHD": 62,
    "QGOMm%W@": 85,
}

def get_dashes(st):
    size, dashes = 0, ""
    for s in st:
        for chs in character_size:
            if s in chs:
                size += character_size[chs]
                break
        size += 50
    while size < 2000:
        dashes += "-"
        size += 60
        if size < 2000:
            dashes += " "
            size += 37
    return dashes

test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
  test += f"{i} {get_dashes(i)}"
print(test)
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your eval job has completed with return code 0.

random - - - - - - - - - - - - - - - Text lengths - - - - - - - - - - - -with - - - - - - - - - - - - - - - - - -dashes - - - - - - - - - - - - - - - 
rare saddle
dull terrace
#

oop should have been new lines

slate swan
#

#bot-commands ?

final iron
#

Fuck

rare saddle
slate swan
dull terrace
#

!e

character_size = {
    "lij|' ": -13,
    "![]fI.,:;/\\t": 0,
    '`-(){}r"': 10,
    "*^zcsJkvxy": 35,
    "aebdhnopqug#$L+<>=?_~FZT": 45,
    "SBPEAKVXY&UwNRCHD": 62,
    "QGOMm%W@": 85,
}

def get_dashes(st):
    size, dashes = 0, ""
    for s in st:
        for chs in character_size:
            if s in chs:
                size += character_size[chs]
                break
        size += 50
    while size < 2000:
        dashes += "-"
        size += 60
        if size < 2000:
            dashes += " "
            size += 37
    return dashes

test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
  test += f"{i} {get_dashes(i)}\n"
print(test)```
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your eval job has completed with return code 0.

001 | random - - - - - - - - - - - - - - - 
002 | Text lengths - - - - - - - - - - - -
003 | with - - - - - - - - - - - - - - - - - -
004 | dashes - - - - - - - - - - - - - - - 
dull terrace
#

the with one is longer 😤

slate swan
#

that is so overcomplicated

tidal hawk
slate swan
dull terrace
#

but that doesn't look neat, i want the same length so i can add info after

tidal hawk
slate swan
tidal hawk
#

Only thing what it gaves me ->

slate swan
tidal hawk
#

disnake

slate swan
#

you can check in there help channels

#

i doubt its a problem with the lib

#

but they know more about the lib

dull terrace
#

uhm

item - - - - some thing here
another item - - - - - - - another thing here related to item
x - - something

VS.

item - - - - - - - - - - - - -some thing here
another item - - - - - - - another thing here related to item
x - - - - - - - - - - - - - - - something

slate swan
#

ah well that's something else

dull terrace
#

there was some reason i ruled out using fields for it but i can't remember why

tidal hawk
hoary cargo
#

uncanny why so many dashes why

pliant gulch
unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

001 | first     fourth    
002 | second    fifth     
003 | third     sixth     
slate swan
#

what does zip even do?

final iron
#

!d zip

unkempt canyonBOT
#
zip

zip(*iterables, strict=False)```
Iterate over several iterables in parallel, producing tuples with an item from each one.

Example:

```py
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
...     print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
```...
slate swan
#

ic

final iron
#

I don't see 💀

slate swan
#

poor you i guess

slim ibex
#

enumerate(zip()) moment

pliant gulch
#

I'll fix that rq

#

!e ```py
first = ["first", "second", "third"]
second = ["fourth", "fifth", "sixth"]

for f, s in zip(first, second):
print(f"{f:10s}{s}")

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

001 | first     fourth
002 | second    fifth
003 | third     sixth
pliant gulch
#

huh

#

I guess it's just this codeblock then

slate swan
#

how are they not aligned

pliant gulch
#

The codeblock has lines

slim ibex
#

!e


names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]

for i, (name, age) in enumerate(zip(names, ages)):
    print(i, name, age)
unkempt canyonBOT
#

@slim ibex :white_check_mark: Your eval job has completed with return code 0.

001 | 0 Alice 24
002 | 1 Bob 50
003 | 2 Charlie 18
pliant gulch
#

I'm assuming it's that

slim ibex
#

they look aligned to me

slate swan
#

same

slim ibex
#

maybe cuz I’m on phone

slate swan
#

lol the font

slim ibex
#

ikr

pliant gulch
#

😔 they aren't aligned for me and it's driving me crazy

slim ibex
#

Lmao

#

Linux user moment pydis_peek

slate swan
#

sucks for you

slim ibex
#

jk jk

fervent shard
#

???
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'create_dm'``````py @bot.command(aliases=['t']) async def ticket (ctx: commands.Context, member: discord.Member = None): channel = await member.create_dm() await channel.send("hi this is a test")

slate swan
#

member is None

slim ibex
#

your member is none

fervent shard
#

oh right-

slate swan
#

NoneType doesnt have such an attr since member is None

pliant gulch
#

No need to manually create the dm

slate swan
#

if you want it to be a member or the author just make member have a value of author

pliant gulch
#

You can just call await member.send(...)

slate swan
#

that as well its kinda useless

dull terrace
#

!e

chr_sizes = {' ': 91, "'.": 128, 'i': 132, '|': 134, ':': 138, '!I': 145, 'j;': 146, 'l': 147, ',': 155, 'f': 162, '[]': 164, 't': 168, 's': 213, '<>': 222, 'z': 228, 'c': 231, '*': 238, 'e': 239, 'a': 241, '~': 244, '?': 245, '/o': 246, '\\': 251, 'g': 252, 'b': 253, 'dpq': 254, 'k': 255, 'nu': 256, 'yh': 257, 'v': 260, 'x': 262, '=': 264, 'L': 269, 'S': 282, '+': 283, '$': 285, 'F': 288, 'C': 291, 'T': 292, 'J': 293, 'E': 294, '_': 296, 'Z': 302, 'P': 309, 'G': 311, 'B': 312, 'D': 318, '#': 324, '^K': 326, 'R': 328, 'AXQO': 332, 'U': 334, 'VYNH': 338, '&': 345, 'm': 367, '%': 370, 'w': 377, '@': 380, 'M': 384, 'W': 458}

def get_dashes(st):
    size, dashes = 0, ""
    for s in st:
        for chs in chr_sizes:
            if s in chs:
                size += chr_sizes[chs]
                break
    while size < 3000:
        dashes += "-"
        size += 60
        if size < 3000:
            dashes += " "
            size += 37
    return dashes

test = ""
for i in ["random", "Text lengths", "with", "dashes"]:
  test += f"{i} {get_dashes(i)}\n"
print(test)```
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your eval job has completed with return code 0.

001 | random - - - - - - - - - - - - - - - - - 
002 | Text lengths - - - - -
003 | with - - - - - - - - - - - - - - - - - - - - - -
004 | dashes - - - - - - - - - - - - - - - - -
dull terrace
#

god dammit

slate swan
dull terrace
#

W | |

#

idk the sizes look right, W seems over 4x larger than space

#

oh i didn't update the - and space size lower down derp

pliant gulch
#

!e ```py
first = ["first", "second", "third"]
second = ["fourth", "fifth", "sixth"]

for foo, bar in zip(first, second):
print(f"{foo.ljust(10, '-')}{bar}")

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

001 | first-----fourth
002 | second----fifth
003 | third-----sixth
pliant gulch
#

They aren't aligned on my screen, but I am assuming they are 😩

#

For some reason my discord client want's to give me OCD

dull terrace
#

okay fml

#

yeah idk

dull terrace
#

i think they're called context menus

slate swan
#

slash commands

slate swan
dull terrace
slate swan
slim ibex
#

they are application commands

slate swan
#

yes

slim ibex
#

but not slash commands

slate swan
#

yes

#

its in there repo

#

if youre searching for examples there git

olive osprey
#

Hello, is there a way to get the avatar url in jpg instead of png?

slate swan
#

youre welcome

pliant gulch
#

Just remembered I need to add context menu commands to my wrapper

#

😔, no more procrastination after 2day

slim ibex
#

we got u Andy

#

rin for life ✊

pliant gulch
#

Member first or Slash commands 😼

dull terrace
#

power just went out for a sec, stupid storm

#

does anyone actually use context menus

#

i never even think to right click a bot pfp

slim ibex
#

idk lmao

#

Prolly some mega ascended human does

dull terrace
#

juman

#

javaman

#

yeash they're useful but so out of the way to get to

pliant gulch
#

It would be good for things like translating a message

#

As context menus are also there for messages

slate swan
pliant gulch
#

That's no fun though 😔

slate swan
#

imagine not having basic models

pliant gulch
#

It's cause they are so tedious to add, albeit easy

slate swan
#

and btw why make a discord api wrapper after theyres so much forks etc?

dull terrace
#

do you guys have any bots out right now?

slim ibex
#

Used to

dull terrace
#

what happened?

slim ibex
#

I archived the project and deleted the repo after my discord account got hacked

#

But I still have to bots source code

slate swan
#

why not make a v2?

pliant gulch
slim ibex
pliant gulch
#

get_channel is O(n) 😔

slim ibex
#

I actually was but the other contributor got hacked I think

slate swan
slim ibex
#

Im actually making a bot for my friends new server,

slate swan
pliant gulch
# slate swan how

Because that's how danny decided to do it, instead of having an O(1) cache

slim ibex
#

but I’m waiting for rin 🗿

pliant gulch
#

Same with messages, they don't use hashtables

#

they are also O(n)

slate swan
#

bruh

dull terrace
#

i've only made 1 discord bot so far and it was basically my first serious python project, code is an absolute mess in some places

slate swan
#

i have like 8

#

tied to my name

dull terrace
#

what bots?

slate swan
#

priv bots lol

dull terrace
#

oh okay

olive osprey
#

Hello, is there a way to get the avatar url in jpg instead of png?

cold sonnet
#

the url in png?

dull terrace
#

would probably have to convert it

slim ibex
#

import the function?

#

and we can see your mongo db credentials 🙃

rare saddle
rare saddle
slim ibex
#

What’s the file structure

rare saddle
#

How to import addblack command from blacklist.py file to modmail.py file?

rare saddle
slim ibex
#

from .filename import function?

#

hopefully there is an __init__.py in your directory

rare saddle
rare saddle
rare saddle
slim ibex
#

Sorry I gtg, someone else gotta help you

#

But I’d put an __init__.py file in each directory

rare saddle
hollow urchin
#

can someone help me with something rq

#

what would I change to make profile_name into “username”

final iron
#

Send your code

slim ibex
#

Make the param username

hollow urchin
unkempt canyonBOT
#

Hey @hollow urchin!

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

hollow urchin
#

@final iron dms

#

ill send code

final iron
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

hollow urchin
#

i sent in dms

final iron
hollow urchin
#

yes

final iron
#

See profile_name in the function params?

cold sonnet
#

how do I pass an async check to bot.wait_for()?

hollow urchin
#

which line

final iron
slim ibex
#

!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**...
cold sonnet
#

yeah async check how

hollow urchin
final iron
#

🗿

slim ibex
#

🗿🗿

hollow urchin
#

🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿🗿

cold sonnet
#

stop

hollow urchin
#

anyways can you help

final iron
#

No

slate swan
hollow urchin
#

bruh

slim ibex
final iron
slate swan
#

we dont spoonfeed here if you cant do it yourself leave

cold sonnet
#

panda

#

I might've found a behaved person

#

how do you pass an async check to a wait_for

hollow urchin
#

ill do my own research for once

final iron
hollow urchin
#

ai

final iron
#

In the case you provided it should be username

slate swan
cold sonnet
#

yes

cloud dawn
# hollow urchin I change that?

What zilo is trying to say, this is pretty basic, think about it. Just change all the profile_name in the code to username

cold sonnet
#

ctx.year = await self.bot.wait_for("message", check=check, timeout=60.0)

#

async def check(m: str):

slate swan
#

wouldnt that work?

cold sonnet
#

is that a guess

#

you don't call the function yourself

cloud dawn
slim ibex
#

It’s a coroutine so it’s already awaiting yeah

slate swan
#

no

cold sonnet
#

I got the traceback allocation error from the source code

cloud dawn
cold sonnet
#

it is

#

I'm not dumb yert

slate swan
#

if you have 2 coros in a line you have to wait both of them

cloud dawn
cold sonnet
#

lemme do it again so the error comes out

#
C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\disnake\ext\commands\common_bot_base.py:106: RuntimeWarning: coroutine 'Birthday.birth.<locals>.check' was never awaited
  super().dispatch(event_name, *args, **kwargs)  # type: ignore
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
#

await the coro lol

cold sonnet
#

you don't call it yourself

#

the api does it 💀

slate swan
#

wdym does check call the func?

cold sonnet
#

no, you just pass in the function

slate swan
cold sonnet
#

meant source code

slate swan
#

nah youre tripping

cold sonnet
#

guess it's time for in-source code error handling

cloud dawn
cold sonnet
#

call_coroutine_threadsafe?

#

I've got myself an example, wait

final iron
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
final iron
#

This

#

Allows you to run the coro without awaiting it

cold sonnet
#
    def leave(error):
        coro = vc.disconnect()
        fut = asyncio.run_coroutine_threadsafe(coro, bot.loop)
        try:
            fut.result()
        except:
            pass
#

this'd work too

cloud dawn
#

What do you even need to await inside a check?

final iron
#

I guess

cold sonnet
cloud dawn
#

Why would you need a send there.

cold sonnet
#

why not

cloud dawn
hollow urchin
#

The more I do stuff on my own I realize how sped I am.

cold sonnet
#

ey don't question my logic, question how I'm doing it

umbral night
#

how would i use a hex code to colour an embed?

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
pliant gulch
cold sonnet
#

to the source code

#

ye

subtle dirge
#
Ignoring exception in command wordle:
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 "main.py", line 73, in wordle
    rewordle.play(WordleSolver())
TypeError: play() missing 1 required positional argument: 'solver'

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: TypeError: play() missing 1 required positional argument: 'solver'
cold sonnet
#

if that line gets the await error, it awaits the check

subtle dirge
#

Ay ideas?

subtle dirge
#

ret = await coro(*args, **kwargs)?

slate swan
#

!e

def function(argument):
    print(argument)

function()
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 | TypeError: function() missing 1 required positional argument: 'argument'
umbral night
subtle dirge
#

whats this?

slate swan
slate swan
subtle dirge
#

what am I doing wrong?

umbral night
#

like

subtle dirge
slate swan
umbral night
cold sonnet
#

super().dispatch(event_name, *args, **kwargs) # type: ignore
k well I don't know what this means but we're getting there

umbral night
#

oh

slate swan
umbral night
#

ik

slate swan
#

defualt is dark grey

umbral night
#

like to make that blue into the colour next to it

#

to make it invisible / transparent

slate swan
#

doubt you can

#

the mobile and pc clients both have different color of grays in the themes

umbral night
#

got it!

pliant gulch
#

The hex code is 0x36393F for the discord's background

cold sonnet
#

BetterDiscord users

final iron
cold sonnet
#

yes

cloud dawn
#

We're not really allowed to suggest betterdiscord here since they violate tos

cold sonnet
#

yeah, it's bad guys

#

harmful

#

no BetterDiscord please

slate swan
#

not secure at all

cold sonnet
#

IP grabbers everywhere

slate swan
#

to have custom or pirated clients

cold sonnet
#

This function returns the first event that meets the requirements...

#

it's a scam

#

or I'm just dumb

#
    @commands.command()
    async def birth(self, ctx):
        def check(m: disnake.Message):
            content = m.content
            if content.isnumeric():
                if int(content) < 2022 and int(content) > 1980:
                    return True
                else:
                    coro = ctx.send("**Az IGAZI születési éved?**")
                    fut = asyncio.run_coroutine_threadsafe(coro, self.bot.loop)
                    try:
                        fut.result()
                    except Exception as e:
                        raise e
                    return False
```first event that returned False shut the whole thing down
pliant gulch
#

👁️ 👁️ , your check function is inside of a coroutine one

#

Just turn it into a coroutine function and await it inside of birth

cold sonnet
#

now what

pliant gulch
#

now await the ctx.send instead of whatever the hell that is

cold sonnet
#

only allowed within async function

#

can't make check an async function

pliant gulch
#

why not

cold sonnet
#

cuz how do I pass it to wait_for

pliant gulch
#

Ah your passing this to wait_for

cold sonnet
#

Ahha moment

#

idrk what to do

#

if I type like 2005 it succeeds

#

if I type 1960 nothing happens

pliant gulch
#

Do you get any errors at all

cold sonnet
#

no

#

and I don't even have an error handler

pliant gulch
#

I would just get rid of the future.result stuff, just do something like self.bot.loop.create_task(coro)

#

Add that to the else statement

cold sonnet
#

sure

pliant gulch
#

and make sure to return False after it

cold sonnet
#

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'create_task'

#

shit

pliant gulch
#

self.bot.loop

cold sonnet
#

yes

#

seems like working

#

other way could be outdated

#

now the bot's forcing me to type something between 1980 and 2022

pliant gulch
#

isn't that what you wrote

cold sonnet
#

yes

pliant gulch
#

👁️ 👁️ so now it's working

cold sonnet
#

I love the way it works so much

#

it's running through 3 classes after one-another

#

and passing through the results

#

so at the end they all go to one database

#

PepeCoffee -> vibing -> bot

final iron
#

Anyone got a discord bot I could work on

#

I'm bored out of my tree

slim ibex
#

learn a new language

#

rust will keep you occupied

final iron
#

Nah

boreal ravine
#

@slate swan

#

F

slim ibex
#

^

boreal ravine
final iron
#

Yours is probably too advanced

dull terrace
#

Without using links

#

I'm 99% sure that it's impossible

left crater
#

thats pretty easy

#

just use file paths

umbral night
#

is it possible to do this?

#

like ping myself

#

@left crater

left crater
#

in an about me?

umbral night
left crater
#

let me try something

umbral night
#

thx

left crater
#

it says i ping u but if u look at my profile its just a bunch of numbers

#

@umbral night

umbral night
#

hm

#

damn

#

alright thanks

dull terrace
left crater
#

why not?

frank tartan
#

how can I open a chrome tab, wait, then close it?

    subprocess.call([CHROME, "https://youtube.com"])
    await asyncio.sleep(50)
    os.system('taskkill /im chrome.exe /f')

that is what I've tried, but chrome doesnt close

umbral night
#

is there an easier way to make it so i can say !Help and !HeLP (with mixed caps incase of an accident or whatever) and it works?

#

without having to add a million aliases

frank tartan
umbral night
#

thx

frank tartan
# umbral night thx

Now this will make your bot take a little more to respond, but just add

case_insensitive=True

to the line where you define bot/client, it should look something like this

bot = commands.Bot(command_prefix="!", case_insensitive=True)
umbral night
#

awesome

slate swan
slate swan
umbral night
#

ty

#

how would i make my text go down a line

#

to make it look easier to read and neater

maiden fable
#

Add a new line?

umbral night
#

yeah

#

ig

#

how would i do that tho

#
async def perks(ctx):
  embed = discord.Embed(title="*perks*", description="`1x boost = custom role+pic&link perms` `2x+ boosts = lowmod+bypassgw reqs`", colour=0x36393F)
  embed.set_thumbnail(url=ctx.guild.icon_url)
  await ctx.send(embed=embed)```
#

this is what i have

maiden fable
#

Just use \n

boreal ravine
#

add a new line

vague grove
#

how can i ban someone and keep their messages?

boreal ravine
#

or use triple quotes ```py
"""
1x boost = custom role+pic&link perms `2x+ boosts = lowmod+bypassgw reqs
"""

boreal ravine
unkempt canyonBOT
#

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

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

ty

boreal ravine
#

set delete_message_days to None

vague grove
#

mkay

umbral night
maiden fable
#

Yea

umbral night
#

by pressing enter?

maiden fable
#

No

#

Add \n

umbral night
#

where

slate swan
#
await send(content="Hunter\nuwu")```
umbral night
#
async def perks(ctx):
  embed = discord.Embed(title="*perks*", description="`1x boost = custom role+pic&link perms` `2x+ boosts = lowmod+bypassgw reqs`", colour=0x36393F)
  embed.set_thumbnail(url=ctx.guild.icon_url)
  await ctx.send(embed=embed)```
umbral night
slate swan
#

yeah

umbral night
#

well now i have this

slate swan
#

backslash = \

oblique laurel
#

Embeds cant use \n

slate swan
frank tartan
#

how can I open a chrome tab, wait, then close it?

    subprocess.call([CHROME, "https://youtube.com"])
    await asyncio.sleep(50)
    os.system('taskkill /im chrome.exe /f')

that is what I've tried, but chrome doesnt close

oblique laurel
#

\:) vs :)

oblique laurel
frank tartan
slate swan
oblique laurel
#

Ig i confused the two lol

maiden fable
bold surge
#

Uh so I have await member.edit(nick = unidecode.unidecode(str(member.name))) which according to the nextcord docs, should work as it only passes in the nick param... although I get nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Timeout must be a "datetime.datetime" or "datetime.timedelta"not _MissingSentinel even though im never using timeout

glacial zealot
umbral night
#

how do i fix this

#

discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently.

quick gust
#

you got rate limited

#

are u on replit?

umbral night
#

so how do i fix it

umbral night
quick gust
#

you cant, you just have to wait

umbral night
#

damn

native wedge
#

and just wait

umbral night
quick gust
#

gonna frequently get rate limited on replit

umbral night
#

damn

native wedge
umbral night
#

yeah

#

replit is my best shot rn

native wedge
#

are you following any sort of tutorial

umbral night
#

no?

#

why

native wedge
#

just wondering

umbral night
#

mk

native wedge
#

also dont put your discord bot token on the actual code itself

#

store it in an environment variable

umbral night
#

i have

#

ive used replit in the past

#

then tried self hosting on vsc for a bit

#

but now that isn't an option

#

so back to replit + uptime robot

final iron
#

Oracle free tier

quick gust
#

or AWS free tier

pliant gulch
#

AWS doesn't have a free tier, they have a free trial

#

At least I don't think so? But I'm probably wrong

#

Oh, wait a free tier is a free trial

quick gust
#

Yeah

#

AWS has 750 hours for each month or something

#

I forgot

maiden fable
#

@umbral night u can get a free Oracle VPS for life if u got a credit card 👀

umbral night
#

nope

#

i mean free free

#

like signup with no card or none of that

maiden fable
#

Idk then

umbral night
#

how could i do something like this

#

command with no prefix

#

@maiden fable

maiden fable
#

!d discord.on_message

unkempt canyonBOT
#

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

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
maiden fable
#

!d discord.Guild.get_member_named

unkempt canyonBOT
#

get_member_named(name, /)```
Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, `None` is returned.
umbral night
#

ah

#

thankyou

umbral night
#

or am i stupid

umbral night
#

so yes?

#

oh

#

client.event

spring flax
#

yeah

umbral night
#

whats after that

spring flax
#

if you're doing client.event you'd need to do client.process_commands(message) also then

#

what do you want to do?

umbral night
#

ah

#

this

#

@spring flax

spring flax
#

uhhh

#

well I want to ask why do you want that?

umbral night
#

i like it

spring flax
#

just for fun or..? Because that will be triggered everytime a message is sent

umbral night
#

?

#

no every time i say "vest" or someones name

#

not just anyone

#

only people i add to the code

#

admins mods etc

#

it'll ping them

spring flax
#

you would require their names then

umbral night
#

yeah

spring flax
#

like name_list = ['vest', ....]

umbral night
#

ok

#

so

@client.event()```
spring flax
#

not the ()

umbral night
#

oh

pliant gulch
#

If you want all commands to not required a prefix you could also pass an empty string to command_prefix

umbral night
#

only this one

spring flax
#

and then

@client.event
async def on_message(message):
  if message.content in [a name list variable]:
    member = await bot.getch_member(user ID)
      await message.channel.send(member.mention)
#

you'd need a name list variable, and likely a dictionary with their name : id

umbral night
#

uh

spring flax
#

i mean you have to get the member objects of each of the people you want it to work on

umbral night
#

yeah

spring flax
#

so a list and dictionary can do that

tiny ibex
#

How to receive attachments to Slash commands??

#

In disnake

umbral night
#
@client.event
async def on_message(message):
  if message.content in name_list = 'vest', 'example', 'example':
    member = await bot.getch_member(user ID)
      await message.channel.send(member.mention)
#

sorry im still new @spring flax

#

so is this what you meant

#

no i have to create-

#

um

#

how do i do this

slate swan
#

Hello trying to make a Anti Token join, basically it bans/kicks people who joined fast and started spamming is that's possible or not?

maiden fable
#

if message.content in ["vest", "example"]:

umbral night
#

ah

maiden fable
unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

umbral night
#
@client.event
async def on_message(message):
  if message.content in name_list = ["vest", "example", "example"]:
    member = await bot.getch_member(user ID)
      await message.channel.send(member.mention)```
maiden fable
# umbral night ah

And in the next line,

member = message.guild.get_member_named(message.content) 
await message.channel.send(member.mention) 
umbral night
#

so will this work? @maiden fable

#

oh

#
@client.event
async def on_message(message):
  if message.content in name_list = ["vest", "example", "example"]:
    member = message.guild.get_member_named(message.content) 
      await message.channel.send(member.mention) 
#

is that the proper indentation? i just guessed

umbral night
spring flax
#

No...

umbral night
#

what

spring flax
#

First of all how big is the serve?

#

Server*

umbral night
#

tiny rn

#

i wanna grow it a bit

spring flax
#

Do you know what lists are?

umbral night
#

not rlly

#

no

spring flax
#

Okay..then before starting i suggest getting a hang of the python basics

#

It'll help substantially

#

!resources

unkempt canyonBOT
#
Resources

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

umbral night
#

bc ive done quite alot so far

spring flax
umbral night
#

yes

spring flax
#

Since it can be a bit complicated or difficult if you're not familiar with the python basics

umbral night
#

alright

#

where do i test?

#

just vsc?

spring flax
quick gust
#

sure, since you don't need to constantly host. Just learn in vsc

umbral night
#

yep im on that page

umbral night
#

where does it get put out?

#

my code*

quick gust
#

what?

#

are you talking about the terminal?

umbral night
#

like once ive done something using basic python

umbral night
quick gust
#

ctrl + ~ to open terminal in vsc

umbral night
#

you know like how youve finished making a command, you move to discord and use the command

#

what do i do once ive finished something using normal python

quick gust
#

yeah, so for basic python it will be controlled from your terminal

umbral night
#

ah ok

spring flax
#

It'd be in visual studio code itself

umbral night
#

alright

#

which one am i supposed to be looking at

#

oh beginner

quick gust
#

Yep

umbral night
#

then what

#

idk which one to do

#

@quick gust @spring flax

frank tartan
#
  guild = client.get_guild(930167279281401906)
  channel = guild.get_channel(944270496659279882)
  msg = await channel.fetch_message(944461110717841448)

thats my code, but I get this error

torpid parcel
#

automate the boring stuff is good

#

@umbral night

frail trellis
#

Who is available to help me with an issue?

spring flax
spring flax
#

What's your current full code?

umbral night
#

how am i able to make my terminal look like this?

#

the one on the left

spring flax
slate swan
#

!d discord.ext.commands.Bot.fetch_guild

unkempt canyonBOT
#

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

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_guild "discord.ext.commands.Bot.get_guild") instead.
slate swan
#

its a coroutine which makes an api call to return a discord.Guild object

maiden fable
spring flax
#

For dynamic cooldown if i have

def custom_cooldown(message):
    if message.author.permissions.manage_messages:
        return None  #bypass mods
    else:
        return commands.Cooldown(1, 900)  # one per 15m
####
@bot.command()
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.guild) #one per fifteen minutes per guild if author not a mod
async def s(ctx):
  pass
maiden fable
#

Mhm?

spring flax
#

Because i put bucket type guild, if a nornal user firsts uses the command and triggers the cooldown, then a mod can't too and has to wait

maiden fable
#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

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

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

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

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
maiden fable
#

Lemme see...

spring flax
#

Is there anything i can do to change this? Would reinvoke be the only option?

maiden fable
#

There should be another way

#

Ah

#

remove the bucket arg

spring flax
#

I want it to be guild cooldown for normal members, but mods can always bypass

maiden fable
#

Wait

slate swan
#

"maybe"

spring flax
#

So reinvoke?

maiden fable
#

There should be a better way...

#

Lemme see

spring flax
#

I mean i tried finding to no extent.

Whats bad about reinvoke?

maiden fable
#

It is just a waste of resources imho. I mean, raising an error, handling it, revinoking and stuff yk

slate swan
#

Unfortunately, this is the sucky part of the commands extension, you sometimes find yourself doing weird monkey patches and fighting for control over how the extension behaves. The only solution is to either continue that or process commands yourself.

maiden fable
#

.....?

spring flax
slate swan
#

It's pretty simple. Parse the message content yourself. Implement your own command classes. Whatever it is you have to do.

#

Just to be clear, I'm not promoting this approach over feuding with the commands extension

maiden fable
#

Well, dpy allows to make yr own Commands class.. That is why there is a cls arg in the bot command deco

#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
maiden fable
#

cls arg can be used to pass in a custom command class

slate swan
#

Might as well just implement your own @command decorator at that point.

maiden fable
#

No need lol

slate swan
#

Better than passing cls=... for every single command you declare.

maiden fable
#

Hmm true tho

slate swan
#

@command decorator is also pretty minimal, it's literally 3 lines of code.

maiden fable
#

Indeed

maiden fable
slate swan
maiden fable
regal pulsar
#
@bot.command()
async def fight(ctx, member: discord.Member):

    global fighter
    global fighter2

    embed = discord.Embed(
        description=f"""{ctx.author.mention} has challenged {member.mention} to a fight!
Do you want to accept or decline? (yes/no)
"""
    )
    await ctx.channel.send(embed=embed)

    fighter = ctx.author
    fighter2 = member
    p1hp = 100
    p2hp = 100
    dmg = random.randint(10, 30)

    def start_choice_p1(ch1):
        return ch1.author == fighter2 and ch1 in ("yes", "no")

    ans = await bot.wait_for("message", timeout=60.0, check=start_choice_p1)

    if ans.lower() == "yes":

        while p1hp > 0 and p2hp > 0:
            embed = discord.Embed(description=f"{fighter.mention} it is your turn. What would you like to do?")
            await ctx.channel.send(embed=embed)

            async def choice_p1(p1choice2):
                return ctx.author == fighter and p1choice2 in ("hit", "kick")

            p1choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p1)

#
            if p1choice2.content == "hit":
                embed = discord.Embed(
                    description=f"You have hit {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
                )
                await ctx.channel.send(embed=embed)
                p2hp -= dmg
            else:
                embed = discord.Embed(
                    description=f"You have kicked {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
                )

                await ctx.channel.send(embed=embed)
                p2hp -= dmg

            embed = discord.Embed(description=f"{fighter2.mention} it is your turn. What would you like to do?")
            await ctx.channel.send(embed=embed)

            async def choice_p2(p2choice2):
                return ctx.author == fighter2 and p2choice2 in ("hit", "kick")

            p2choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p2)

            if p2choice2.content == "hit":
                embed = discord.Embed(
                    description=f"You have hit {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
                )
                await ctx.channel.send(embed=embed)
                p2hp -= dmg
            else:
                embed = discord.Embed(
                    description=f"You have kicked {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
                )
                await ctx.channel.send(embed=embed)
                p2hp -= dmg

        if p1hp == 0:
            embed = discord.Embed(description=f"{fighter2.mention} HAS WON!")
            await ctx.channel.send(embed=embed)
        elif p2hp == 0:
            embed = discord.Embed(description=f"{fighter.mention} HAS WON!")
            await ctx.channel.send(embed=embed)
#
    else:
        embed = discord.Embed(description=f"{fighter2.mention} has cancelled the fight!")
        await ctx.channel.send(embed=embed)


@fight.error
async def on_fight_error(ctx, error):
    if isinstance(error, asyncio.TimeoutError):
        embed = discord.Embed(description=f"Time's up, the match has been forfeited.")
        await ctx.channel.send(embed=embed)
#

did i mess up the wait_for syntax?

#

cuz it doesnt work

maiden fable
#

Bro

#

!paste exists

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.

regal pulsar
#

oh mb

slate swan
#

Why are your checks async functions?

torn sail
regal pulsar
regal pulsar
#

wait ill try

regal pulsar
#

doesnt work

torn sail
#

The check shouldn’t be async

regal pulsar
#

oh

#

hmm wait

regal pulsar
final coral
#

can you add url in discord embed field name

torn sail
regal pulsar
#

oh

#

HA

#

IT WORKS

umbral night
#

can somebody please help me with making this?

#

where i can put important peoples names in my code and the bot pings them once said in a text channel

#

important people meaning admins, owners, mods etc

#

so i can say the name without using a prefix

#

and i can say it in a sentence

latent widget
#

Does anybody know a online Python IDE?

latent widget
halcyon onyx
#

hello how send message if value is true?

halcyon onyx
#

wait

fiery veldt
#

How to make a scrims bot