#discord-bots

1 messages Β· Page 957 of 1

idle sparrow
#

why

ripe harness
#

i mean yo ucan it has nothing and if u get it working i ll reset it πŸ˜„

maiden fable
#

Haha

unkempt canyonBOT
#

Hey @ripe harness! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

ripe harness
#

aw

idle sparrow
#

lol

maiden fable
#

I was jk bruh

#

does yr token have 3 periods?

ripe harness
#

And i told you i don't care tbh

#

2

maiden fable
#

wait yea 2

#

my bad. hmmmmmm, can u post the part of the token preceding the first period?

ripe harness
#

OTYwODcwODU2NjMwODgyMzA0

idle sparrow
#

eh

#

wtf is going on here

ripe harness
#

do you want the mid one πŸ˜„

idle sparrow
#
 return connected["NightmareFever"]["Config"].find_one({"name":entry})["token"]
#

there is my token see if u can use it

ripe harness
#

It's a blank example just on ready func and this token and it is bullying me

slate swan
maiden fable
#

this yr bot?

#

@ripe harness

ripe harness
#

y

idle sparrow
#

oh wow

maiden fable
slate swan
maiden fable
#

weird, try resetting the token and copying again

ripe harness
#

did it 5 times 😦

maiden fable
#

prolly it isn't being copied and u r pasting the old token

austere herald
#

This message here should be ephemeral

#

For whatever reason it isn't

#

This also applies to my error handler

#

Which is here:

import traceback
from io import StringIO
from typing import Union

import discord
from discord import Interaction, app_commands
from discord.app_commands import AppCommandError, Command, ContextMenu


async def on_app_command_error(interaction: Interaction, command: Union[Command, ContextMenu], error: AppCommandError):
    error = getattr(error, "original", error)

    match error.__class__:
        case app_commands.CommandNotFound:
            return
        case app_commands.MissingPermissions:
            msg = "__This command requires the following permissions:__\n**{}**".format(
                "\n".join(i.replace("_", " ").replace("guild", "server").title() for i in error.missing_permissions)
            )
        case app_commands.CheckFailure:
            msg = str(error)
        case _:
            f = discord.File(StringIO(traceback.format_exc()), filename="exception.py")
            await interaction.response.defer()
            return await interaction.followup.send(file=f, ephemeral=True)

    return await interaction.response.send_message(msg, ephemeral=True)
sick birch
#

Pretty sure followups can't be ephemeral

#

Only direct responses

austere herald
#

Hm

maiden fable
#

!d discord.Interaction.followup

unkempt canyonBOT
sick birch
#

It's a webhook

maiden fable
#

they can be

#

Yea webhooks can send ephemerals

sick birch
#

ah

maiden fable
#

Wait nvm

austere herald
#

Interesting

maiden fable
#

seems like I am prolly confused

#

Oh wait I ain't wrong

sick birch
#

Yeah make sure it's a WebhookType.application

maiden fable
#

Yea

#

Prolly its not

austere herald
#

It's an interaction followup

#

Should be

maiden fable
#

BTW @sick birch any idea how discord handles ratelimits for slash commands and context commands since we still need to defer and stuff so does deferring also count as a ratelimiting request?

austere herald
#

Why this is interesting

#

On some commands the ephemeral followup send works, others don't

#

Here's the commands source code

slate swan
#

why use followup

maiden fable
#

can u print inter.followup.type?

#

Cz he is deferring the response.....?

austere herald
#

WebhookType.application

maiden fable
#

hm it does print the correct type

slate swan
maiden fable
#

wait, its a slash command nvm

grim oar
#

Ben.

slate swan
#

10

#

nvm

grim oar
#

The dog bro

#

Talking ben

slate swan
#

lmao

grim oar
#

Funniest shit I have ever seen

austere herald
#

Fixed

#

You can't send ephemeral followups

maiden fable
#

Lmao some people do be remembering old cartoons

maiden fable
slate swan
#

what measures would you guys suggest for anti-raiding functionality

grim oar
#

He drug dealer of talking tom

unkempt canyonBOT
#

Cooldowns in discord.py

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

from discord.ext import commands

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

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

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

slate swan
#

all my commands have cooldowns

maiden fable
#

ah that way

grim oar
#

Ben.

slate swan
maiden fable
#

lmao ngl Ben 10 > Talking Ben for whatever reasons

#

But won't continue this talk here

grim oar
#

No

slate swan
flat solstice
#

is there a tag with a example error handler? that also includes d.py V2 errors?

maiden fable
#

Nope

wary hatch
#

is there a specific channel for d.py support or would it just be the regular help channels?

maiden fable
maiden fable
slate swan
#

and that exclamation mark made it all more worse

maiden fable
#

I used to hang out in the help channels of that server most of the time when I was new to bot making, so ik the pains 🀷

austere herald
#

Same

solid summit
#

Its not that bad

slate swan
maiden fable
#

"extra hell" Well, a bit mild but no comments

slate swan
#

lmao

#

they give more of a brainfuck rather than helping

hushed galleon
#

i do think the expectation there of learning OOP and fundamentals is higher

solid summit
#

They just want people to understand python beforehand

maiden fable
#

Well from my experience, they don't like beginners and only help those people whole heartedly who are good in Python

maiden fable
#

I mean some people do help beginners but still 🀷

slate swan
maiden fable
#

Haha

solid summit
#

Dpy server

maiden fable
hoary cargo
#

in dpy server no one will help you without basic knowledge

austere herald
#
  1. We're glad to help where we can, but come with at least a basic understanding of Python.
  • It's recommended to complete a smaller project first. Some of the techniques used in the library are difficult for beginners to understand and could be potentially frustrating or confusing.
  • For a more nuanced definition, please check faq
maiden fable
slate swan
#

I will just join back and annoy them now

austere herald
#

discord.py actually fueled me with the motivation to continue learning Python

sick birch
maiden fable
flat solstice
#

yeah my experience in dpy's server ranges wildly, most of the time I end up with more problems than i started with unless I'm going there for a very specific very niche problem, the handful of times I've received decent support have alwys been when Danny is online and in one of the help channels, then they are all helpful

austere herald
slate swan
slate swan
sick birch
#

You do you

maiden fable
#

I mean, I myself learnt most of the stuff by looking in the help channels

dull terrace
#

When you use an consumable object in your discord bot game that collects materials for you and for some reason enemies around you start exploding too aniblobsweat

maiden fable
#

what

hoary cargo
hoary cargo
dull terrace
#

i can just tell this bug is going to be an ~ordeal~ to fix

maiden fable
slate swan
sick birch
#

i would never

wary hatch
maiden fable
#

Prolly like 5, max

maiden fable
sick birch
#

i have a backup storage drive with all my memes on it πŸ˜„

wary hatch
#

ok awesome

maiden fable
#

Hahaha well I am too lazy to rearrange all the code pics and memes into different albums

wary hatch
#

im trying to make my bot run an ffmpeg command using the ffmpy library, but everytime it does, the entire bot stops doing anything until its done, i've tried putting it into an async function and await it but that didn't work, does anyone have any suggestions to get around this?

maiden fable
#

and yea, also make space for some school work pics out of those code pics

slate swan
unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

sick birch
slate swan
#

lmao

maiden fable
#

This is what is happening with your bot @wary hatch

#

use VoiceChannel.connect and VoiceClient.play with opus or smth idk

#

shouldn't be blocking then

wary hatch
maiden fable
#

Show code

wary hatch
#

okedoke

hoary cargo
#

ngl, i find voice stuff quite troublesome. ffmpeg and stuff like this damn, better just give up

maiden fable
#

true, but I am still waiting for voice receive in disnake pithink

austere herald
#

disnake

sick birch
slate swan
wary hatch
# maiden fable Show code
async def fix_vid(input):
    ff = FFmpeg(
        inputs={input: None},
        outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
    )
    ff.run()
    return

await fix_vid(input)

this is everything relevant, the fix_vid call is in an on_message event that grabs an attachment and saves it, didn't think it'd be necessary to send since it's quite large

maiden fable
#

EQ has been busy with irl stuff so he isn't able to spend time on lib dev

austere herald
wary hatch
#

i have not

maiden fable
slate swan
#

EQ is a cool guy no cap

maiden fable
#

Yup

wary hatch
sick birch
wary hatch
#
import discord
import os
import urllib.request
import asyncio
import subprocess
from ffmpy import FFmpeg
from discord.ext import commands
wary hatch
maiden fable
#

But anyways, either way, make it an async function and use loop.run_in_executor where loop = bot.loop

#

!pypi ffmpy

unkempt canyonBOT
maiden fable
#

"simple" ofc

sick birch
#

Why not put that in a seperate application? like flask or something

#

then just use aiohttp and you won't worry about having it block

maiden fable
#

I don't think its maintained anymore tho

wary hatch
slate swan
#

!pypi flask

unkempt canyonBOT
#

A simple framework for building complex web applications.

sick birch
maiden fable
slate swan
#

flask is lovely easy

slate swan
sick birch
#

Or, if you know JS/TS already you can use express if you'd like

maiden fable
maiden fable
wary hatch
#

i dont understand how flask is relevant to my problem

maiden fable
wary hatch
#

not a diss to you, i am just unfamiliar

slate swan
slate swan
maiden fable
slate swan
#

how do i set the author image again?

#

i forgor πŸ’€

maiden fable
slate swan
#

(on an embed)

maiden fable
unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
sick birch
slate swan
sick birch
#

And use aiohttp to wait for server response

slate swan
#

me not like using embed functions

maiden fable
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
maiden fable
#

!d discord.Asset.url

unkempt canyonBOT
maiden fable
#

(:

wary hatch
slate swan
maiden fable
slate swan
#

uhh discord.Embed.set_author is a function?

slate swan
maiden fable
#

method

slate swan
#

yes

#

and it wouldnt matter? just set it to an instance of the class

wary hatch
#

is there any objectivity to whether i should use flask vs loop.run_in_executor

maiden fable
#

I would prefer the second one

slate swan
#

bro scroll up

maiden fable
#

They do return self True

slate swan
stiff nexus
#
discord.PermissionOverwrite(discord.Permissions.all==False)
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 384, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/cogs/events.py", line 200, in on_command_error
    raise error
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 182, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/cogs/owner.py", line 175, in setupbot
    guild.default_role: discord.PermissionOverwrite(discord.Permissions.all==False),
TypeError: __init__() takes 1 positional argument but 2 were given

maiden fable
#

what

#

the

slate swan
austere herald
#

/home/runner - don't use replit

maiden fable
slate swan
#

so technically i am right in a sense

maiden fable
slate swan
#

I swear 3 people asked their questions in the dpy server and never got an answer there and came here in the past 10 mins

#

dpy server > pydis

maiden fable
maiden fable
sick birch
#

Is that really needed

slate swan
sick birch
#

A simple http request will do

maiden fable
sick birch
#

Hardest part is figuring out how to transmit non text data

maiden fable
maiden fable
#

Too much work receiving binary and decoding it both the client and API side but then, run_in_executor is the easiest way

slate swan
maiden fable
#

Lmao

#

I still never understood how to send image data over to an API ngl

lament mesa
#

Files can be sent in post requests

maiden fable
#

Yea

#

I still remember when I tried to use the Fetch API browsers provide lmao

lament mesa
wary hatch
#

when making the loop thing, what would i set the loop to?

maiden fable
#

Uhh stop before I start to question my decision to start programming

maiden fable
#

nvm internals

wary hatch
#

i tried that and it said not defined

maiden fable
#

Well πŸ‘€

opal prawn
#

i need a bot that will say a random member when i ask it to

maiden fable
#

!d random.randrange

unkempt canyonBOT
#

random.randrange(stop)``````py

random.randrange(start, stop[, step])```
Return a randomly selected element from `range(start, stop, step)`. This is equivalent to `choice(range(start, stop, step))`, but doesn’t actually build a range object.

The positional argument pattern matches that of [`range()`](https://docs.python.org/3/library/stdtypes.html#range "range"). Keyword arguments should not be used because the function may use them in unexpected ways.

Changed in version 3.2: [`randrange()`](https://docs.python.org/3/library/random.html#random.randrange "random.randrange") is more sophisticated about producing equally distributed values. Formerly it used a style like `int(random()*n)` which could produce slightly uneven distributions.

Deprecated since version 3.10: The automatic conversion of non-integer types to equivalent integers is deprecated. Currently `randrange(10.0)` is losslessly converted to `randrange(10)`. In the future, this will raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
wary hatch
#

does it matter if its in a cog?

maiden fable
#

self.bot.loop

wary hatch
#

like i know cog makes it different

#

ohh

maiden fable
#

or ctx.bot.loop

wary hatch
#

aaaaaaaa i did it and it still doesnt work aaaaaaaaaaaaaaa!!!!

#
async def fix_vid(self, input):
    ff = FFmpeg(
        inputs={input: None},
        outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
    )
    loop = self.client.loop
    loop.run_in_executor(ff.run())
    return

so i goofed here right

maiden fable
#

yes

wary hatch
#

i knew it

maiden fable
#

u need to do

def fix_vid(self, input):
    ff = FFmpeg(
        inputs={input: None},
        outputs={f'new_{input}': '-c:a copy -c:v libx265 -crf 20'}
    )
    ff.run()

And then, in yr command, do self.bot.loop.run_in_executor(None, fix_vid, "some vid file prolly")

#

!d asyncio.loop.run_in_executor

unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
wary hatch
#

oh

#

def and not async def?

maiden fable
#

yea

wary hatch
#

do i await self.bot.loop.blahblah?

maiden fable
#

yes

hoary cargo
#

facepalm still at ffmpeg stuff huh

wary hatch
#

it works!!!!!!!!!! thank you!!!!!!!!! PRETTY

maiden fable
#

cool!

dull terrace
#

with or without blank spaces in code ablobsweats

slate swan
dull terrace
#

black auto format doesn't get rid of the spaces suspicious

#

otherwise identical

dull terrace
slate swan
dull terrace
#

50% of the time you ask coders a question they go on a tangent smh

slate swan
#

and no new lines is better

dull terrace
#

pep8 tells you to use them sparingly tho

#

is that sparingly

maiden fable
slate swan
#

no

dull terrace
#

wheres the pep8 guy

maiden fable
#

plz

slate swan
#

im eating πŸ˜”

maiden fable
#

plzplzplzplz

slate swan
maiden fable
#

oh wow

slate swan
#

mine is 1am

cold sonnet
#

how is a midnight on a half hour

#

it's 6am for me

maiden fable
#

why not

#

Cz I live in India

cold sonnet
#

I didn't know half timezones exist

#

wait a minute

maiden fable
#

He lives in USA or smth idk

cold sonnet
#

it's 0:27 there rn

maiden fable
#

Yea

cold sonnet
#

innit

#

nice

maiden fable
cold sonnet
#

no

#

not particularly

#

actually, I'm frankly far away from the land of the British

#

jk literally one country away

#

!ot

unkempt canyonBOT
slate swan
#
attributes = {
   'name': "commands",
   'aliases': ["help", "helps"],
   'cooldown': commands.Cooldown(1, 3, commands.BucketType.user),
   'hidden': True
} 

help_command = HelpCommand()
help_command.command_attrs = attributes

exception

Traceback (most recent call last):
  File "", line 16, in <module>
    'cooldown': commands.Cooldown(1, 3, commands.BucketType.user),
TypeError: Cooldown.__init__() takes 3 positional arguments but 4 were given```
#

anyone know why?

#

ah wait

#

from 2.0 on cooldown no longer has type as an argument right

final iron
slate swan
#

need to use cooldown mapping

final iron
slate swan
cold sonnet
#

HUH

cold sonnet
final iron
slate swan
#

dont ask how i know he lives there 😳

cold sonnet
#

but I was talking about india

final iron
#

Oh

cold sonnet
#

there's no way

final iron
dull terrace
final iron
#

Personally I like the newlines

#

I think it would be harder to read without them

dull terrace
#

i could have it all on one line but with an f string it would be one long line and less easily readable

slate swan
#

how can i get the message of the user that invoked a help command?

#

i'm subclassing commands.HelpCommand

dull terrace
#

all pep8 says is use them sparingly suspicious

slate swan
#

i want the bot to reply to the message instead of sending the help embed to the destination

quaint epoch
dull terrace
#

you probably need to find whatever id the message is that you want, fetch the message and then do <message you fetched>.reply(stuff)

slate swan
quaint epoch
slate swan
#

i'm subclassing a help command

#

ctx doesn't exist

maiden fable
#

it does

quaint epoch
#

yeah

maiden fable
#

self.context

slate swan
#

wait what

quaint epoch
#

how else will you send the message lol

maiden fable
#

!d discord.ext.commands.HelpCommand.context

unkempt canyonBOT
slate swan
abstract kindle
#
class User:
    def __init__(self, bot, user_id: int, name: str, role: Role):
        self.bot = bot
        self.user_id = user_id
        self.name = name
        self.in_game = False
        self.isBot = False
        self.role = role

How would I make it so that upon init this class identifies which role a user has

dull terrace
#

you need a message object to reply to...

slate swan
slate swan
quaint epoch
slate swan
#

ok well thanks guys

quaint epoch
#

but i prefer to use commands.group or bot.group for help commands

#

but u do u

dull terrace
#

this is probs about the same amount but depending on complexity

slate swan
dull terrace
#

but if statements already have an indentation which is kind of a natural separator, at least that was my thinking

dull sorrel
#

How to send custom emojis?

dull terrace
#

get_emoji(emoji_id)

#

to get the object

dull sorrel
#

Is that the only way?

#

Then str it, right?

dull terrace
#

if it's in the same server i think theres some text thing you can send, can't remember

dull sorrel
#

Same server.

dull terrace
#

possibly something like that

dull sorrel
dull terrace
#

just fetch whatever emojis you need at the bot startup and keep in a list or dict, it's what i do

#

doesn't take any time

slate swan
dull terrace
slate swan
dull terrace
#

i guess it's just one if statement logically connected to the above code then it doesn't need a space

#

so 8

#

instead of 5

slate swan
cold sonnet
#

what's player.inventory

dull terrace
#

it's the players inventory wheeze

cold sonnet
#

don't tell me that's a json

#

Olie

dull terrace
#

it's a flat dictionary that is unpacked into a db when it saves

cold sonnet
#

ok

dull terrace
#

otherwise my player class would be dumb af

#

because there are like over 20 inventory items, and variable prices

#

for each item

abstract kindle
#

can anyone help me

vale wing
#

Would anybody like to help me with training an antispam model

#

For the future antispam bot

#

I need some samples of spam and not spam

#

To be more exact around 1k

slate swan
#

how do u make a hyperlink in a text

vale wing
#

It's something like [text](link) or vise versa I always confuse it

slate swan
#

like "hey u cant do this and this watch (hyperlink)this to do verify urself"

vale wing
#

Works only in embeds

vale wing
#

Look at markdown syntax for that

maiden fable
vale wing
#

Ok

hushed galleon
maiden fable
dull terrace
#

what is the logical reason that one is square and one is round?

maiden fable
#

Idk

hushed galleon
#

ultimately it comes down to the shapes and patterns that humans have found in nature

dull terrace
#

ah yes, the square bracketed plant species as we all know

slate swan
#

Hey guys, I have a question.. There is this bot written in JS, I offered to assist but I use dpy with nextcord fork.. is it possible to write a command in another pro lingo?

hoary cargo
#

πŸ—Ώ so you want python help with a js bot

slate swan
#

Heard it was possible

#

No not help, just asking if i could use another language

#

πŸ—Ώ

verbal breach
hoary cargo
hushed galleon
slate swan
#

lmfao

hushed galleon
#

if you're playing around with the doc commands you should use #bot-commands, or you can ask us what you need

verbal breach
#

Oh

slate swan
#

i was tryna help him

#

:'/

verbal breach
#

trying to find syntax for something like

slate swan
#

its ctx.author.id

verbal breach
#

If message.author has this id, do this

#

ah

hoary cargo
#

it has

#

!d discord.Member

unkempt canyonBOT
#

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

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

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

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

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
slate swan
#

ah ok whatever

hoary cargo
slate swan
#

πŸ€” wait he sking for author id

slate swan
hoary cargo
verbal breach
#

so i can do something like

slate swan
verbal breach
#

and itll give me the number?

slate swan
#

it should

hushed galleon
hoary cargo
verbal breach
#

ok

left crater
#
channel = ctx.guild.get_channel(699577970117050399)
    messages = await channel.history(limit=None).flatten()
    for i in messages:
        with open("stuff.txt", "w") as wf:
            wf.write(i.attachments)``````
Ignoring exception in command get:
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 206, in get_all_images
    messages = await channel.history(limit=None).flatten()
AttributeError: 'NoneType' object has no attribute 'history'

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

Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'history'```did they change something?
verbal breach
#

i had the lines for it in my automated bot that i learned went against tos so i deleted code without thinking

#

that the stuff in there could be useful.

hushed galleon
left crater
#

in a command

hushed galleon
#

did you double check the id?

left crater
#

yes

#

i pressed copy id

hushed galleon
#

also are you using your command only in the guild that has the channel?

left crater
#

yeah

#

wait no

#
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
    messages = await channel.history(limit=None).flatten()
AttributeError: 'async_generator' object has no attribute 'flatten'

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

Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'```give me this now
#

@hushed galleon

hushed galleon
#

hm i havent seen async_generator come from channel.history()

#

whats your code now if you changed anything, and what version of dpy are you using?

left crater
#
async def get_all_images(ctx):
    guild = bot.get_guild(699577686795747349)
    channel = guild.get_channel(699577970117050399)
    messages = await channel.history(limit=None).flatten()
    for i in messages:
        with open("stuff.txt", "w") as wf:
            wf.write(i.attachments)```i am using 2.0
torn sail
#

It’s now [message async for message in channel.history(…)]

#

List comprehension

left crater
#

oh ok

#

ill try that

slate swan
#

How to make the warns on other servers different, otherwise it issued a varn on one server, and it is shown on all?
Sql

hushed galleon
#

ah that i hadnt seen in the changelog

slate swan
#

Help me pls

hushed galleon
#

wzr youve been asking that for a bunch of days now right, i sent you an answer in #databases some time earlier

slate swan
#

A

verbal breach
hushed galleon
verbal breach
slate swan
#

didn't see it, sorry

hushed galleon
#

@verbal breach depends on what you named the variable/parameter storing the Message object

slate swan
hushed galleon
#

though whatever it is the parentheses in that if-statement isn't necessary

slate swan
#

πŸ€”

left crater
verbal breach
#
async def on_message(ctx):
  if (message.author.id == dont know what to put here):
    #β€œexample”
#

is this correct

left crater
#

on_message doesnt accept ctx

hushed galleon
#

well i already suggested rewriting your table to use a compound primary key, what issues are you having with that

verbal breach
#
@client.event
async def on_message(message):
  if (message.author.id == dont know what to put here):
    print(ctx.author.id)
muted cliff
#

hello i need help

verbal breach
#

how about this

muted cliff
#

in self bot code

left crater
#

that would be correct

final iron
#

Also no need for the brackets

left crater
#

aint javascript

verbal breach
#

I want it so that on_message. It sees if message.author.id == the authors id. It does something

#

wahhhh

#

T-T

slow fog
#

ass

verbal breach
#

why

final iron
#

You don't need them

verbal breach
#

it doesnt effect it does it?

final iron
#

No but there's no reason to have it there

verbal breach
#

im keeping it like that

#

idc

#

its easy to read for me.

final iron
#

Why...?

hushed galleon
#

if you're a beginner to programming you probably dont need to worry about style, whats more important are fundamentals like variables and functions

verbal breach
#

looks more organized

final iron
verbal breach
#

Thats why im keeping it that way.

slate swan
final iron
#

It depends where you live

hushed galleon
#

i disagree, style is something you can learn later but you cant even begin to make programs without basic understanding of a procedural language

slate swan
hushed galleon
#

people also distinguish them by saying square and round brackets

final iron
slate swan
final iron
slate swan
verbal breach
#
async def on_message(message):
  if (message.author.id == number):
    print(author.id)
#

is this it

hushed galleon
# slate swan bro

according to merriam webster "bracket" can be an alias for parentheses

verbal breach
#

can i use something like author.content

final iron
#

No?

hushed galleon
#

you cant make use of variables without declaring them beforehand

final iron
#

What content would the author have

#

Also you can check that kind of thing in the docs

left crater
verbal breach
#

! content.author

#

!content.author

#

!content

#

its not working

full lily
hushed galleon
#

you'd do !d content, but the docs cant guess what you mean by an arbitrary word "content"

#

as demonstrated

verbal breach
#

ah

#

T-T

hushed galleon
#

the docs are only there to tell you what different objects there are, what attributes those objects have, and sometimes offer examples of how they may be used, but they cant write the actual code you would use in your script

verbal breach
#

!write my code

left crater
verbal breach
#

dam

left crater
verbal breach
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval <code>
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

full lily
#

!e my life decisions

unkempt canyonBOT
#

@full lily :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     my life decisions
003 |        ^^^^
004 | SyntaxError: invalid syntax
verbal breach
#

ah

hushed galleon
verbal breach
unkempt canyonBOT
#

@verbal breach :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     if (message.author.id = num):
003 |         ^^^^^^^^^^^^^^^^^
004 | SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
verbal breach
#

bruh i forgor

left crater
verbal breach
unkempt canyonBOT
#

@verbal breach :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     if (message.author.id == id):
003 |                                  ^
004 | IndentationError: expected an indented block after 'if' statement on line 1
left crater
#

i only need the attachments

slow fog
#

no

hushed galleon
#

what specifically do you need from the attachment? the name of the file, or the contents of the file?

left crater
#

url

verbal breach
#

AHHHHHHHHGGGGGGGGG 😑😑😑😑

hushed galleon
#

!d discord.Attachment.url

unkempt canyonBOT
#

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

hushed galleon
#

print/write that url attribute

left crater
#

print(messages.attachments.url)this will give me an error cuz its a list

hushed galleon
#

then you loop through the list and print the url for each attachment

left crater
#
async def get_all_images(ctx):
    guild = bot.get_guild(699577686795747349)
    channel = guild.get_channel(699577970117050399)
    messages = [messages.attachments.url async for messages in channel.history(limit=None)]
    print(messages)``````
Ignoring exception in command get:
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
    messages = [messages.attachments.url async for messages in channel.history(limit=None)]
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in <listcomp>
    messages = [messages.attachments.url async for messages in channel.history(limit=None)]
AttributeError: 'list' object has no attribute 'url'

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

Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 1183, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 905, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 195, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'url'```
#

message.attachments works btw

#

it just gives me everything

hushed galleon
# verbal breach !e if (message.author.id == id):

!resources < i would highly recommend some beginner guides on python before you start learning how to write a discord bot, because computers can't assume what you're trying to do from a few out-of-context words; its a programming language, so there's a structure to the code that is necessary for computers to understand what it means, and while you dont need to know everything to crush together programs that work, not knowing the fundamentals like variables and control structures will make it very difficult for you to understand what you're writing

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.

left crater
fast vortex
hushed galleon
#

you're referencing message.attachments as you loop over message.attachments at the same time

verbal breach
#

!e

import discord
import os
import requests
import re

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

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

  if (message.author.id == "Gh0st#0726"):
    await channel.message.send("hello, Gh0st.")
  



client.run(os.getenv('TOKEN'))
unkempt canyonBOT
#

@verbal breach :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 'discord'
verbal breach
#

bruh

left crater
#

thats not how eval works my guy

verbal breach
#

wahhhh

unkempt canyonBOT
boreal ravine
#

@verbal breach #bot-commands

hushed galleon
#

well thats not descriptive... regardless the author id is an integer, so you wont be able to compare it to a user name

verbal breach
#

THANKYOU

#

THANKYOU THANKYOU THANKYOU

verbal breach
left crater
#

not the id

verbal breach
#

i have to put this somewhere for me to read

hushed galleon
left crater
#
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 186, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in get_all_images
    messages = [messages.attachment async for messages in channel.history(limit=None)]
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 207, in <listcomp>
    messages = [messages.attachment async for messages in channel.history(limit=None)]
AttributeError: 'Message' object has no attribute 'attachment'```
hushed galleon
#

message history gives you one list, and each of those gives you a list of attachments, so if you want a list of all attachments from all then you need a nested for-loop

verbal breach
#

!e

if (discord.User.id == "#0726"):
  await channel.message.send("hello, Gh0st.")
unkempt canyonBOT
#

@verbal breach :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 | SyntaxError: 'await' outside function
left crater
verbal breach
#

oh

left crater
slate swan
#

it is a discriminator

hushed galleon
slate swan
#

@verbal breach i suggest that before you start coding you learn the basics of Discord and of Python itself

verbal breach
#

!e

if (discord.User.id == "#0726"):
  await message.channel.send("hello, Gh0st.")
unkempt canyonBOT
#

@verbal breach :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 | SyntaxError: 'await' outside function
hushed galleon
sick birch
#

Let's keep the eval spam down please

verbal breach
#

The ling numbr right? Like

hushed galleon
#

oops mb i read it out of context

slate swan
#

πŸ‘

glacial echo
#

man i love modules installing fine on one device but failing on another

glacial echo
#

(because if i think goslate being required but goslate also being dead)

#

(i think)

cloud dawn
glacial echo
sick birch
glacial echo
#

what’s that?

cloud dawn
glacial echo
#

ah

sick birch
#

Common tool used in production. Isolates your code

#

You don't pollute your main system with programming languages, dependencies, random files

glacial echo
#

i mean yeah rn my plan is to just set up a VM

sick birch
#

If you can get a program to work inside docker, it will work anywhere with minimal setup

sick birch
#

Yes. That's why you use docker

glacial echo
#

mhm

sick birch
#

So you don't have to install 20 different things and hope they all work on your system

#

Besides, docker is an important skill to know in the industry

cloud dawn
#

Semi

glacial echo
#

good thing i’m going into the other CS

#

the edible kind

slate swan
#

is there a way to check if payload.emoji is custom or not?

#

on_raw_reaction add btw

slate swan
glacial echo
#

my@pip is up to date

#

smh

verbal breach
#

How to make <member 'id' of 'User' objects> print the actual id instead

slate swan
unkempt canyonBOT
verbal breach
#

yes

cloud dawn
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.id "discord.User.id")
glacial echo
#

what do you mean by actual id

keen lynx
#

i was loading cogs on on_ready event this is probably bad getting rate limted and bot breaking while launching. how should i fix this ?thinkmon

verbal breach
#

i want it to print the actual id instead of <member 'id' of 'User' objects>

slate swan
slate swan
glacial echo
#

oh

#

hmm

slate swan
verbal breach
#

how do i make <member 'id' of 'User' objects> Print the 8384738374 as an example

glacial echo
#

let’s see the code then

#

idk why it would be printing it it weirdly

verbal breach
#
if message.author != client.user:
    await message.channel.send(discord.User.id)
jade jolt
#

right.

verbal breach
#

its not what i actusly want it to do.

#

just as a test run

glacial echo
jade jolt
#

wouldn't it be message.author?

glacial echo
#

true

final iron
slate swan
#

i word stuff weirdly

#

πŸ˜”

slate swan
final iron
#

In an on_message event, message is your instance of the discord.Message class

slate swan
#

just deleted my whole wrapper by mistake...

glacial echo
#

ctrl z ?

slate swan
#

cant lol

jade jolt
#

oh

slate swan
#

the cache impl was so goodπŸ˜”

stuck oyster
#

how can I import a file from my cog to my main.py file

slate swan
#

what

slate swan
# slate swan the cache impl was so goodπŸ˜”
from __future__ import annotations
from typing import Callable, Generic, Iterator, TypeVar
from typing_extensions import Self

from exceptions import DisabledCache

C = TypeVar("C")


class Cache(Generic[C]):
    def __init__(self: Self, *, enabled: bool = False) -> None:
        self.enabled = enabled
        self.cache: dict[str, list[dict[str, str]]] = {}
    
    def __len__(self: Self) -> int:
        return len(self.cache)

    def __iter__(self: Self) -> Iterator[str]:
        return iter(self.cache)

    def cancache(self: Self, m: Callable[..., C]) -> C | DisabledCache:
        if self.enabled:
            return m()
        raise DisabledCache
    
    @cancache
    def save(self: Self, key: int, value: dict[str, list[dict[str, str]]], /) -> None:
        self.cache[key] = value

it was so goodπŸ˜”

jade jolt
#

what it do

stuck oyster
slate swan
#

into a dict

stuck oyster
slate swan
#

if its in a file it would be

from foldername.filename import classname
slate swan
#

show your file dir

slate swan
#

nah

slate swan
#

relative imports need a parent package

#

Ic

#

try it and it would raise an error

slate swan
#

yeah

#

It raise some "package" error

#

yeah

stuck oyster
slate swan
#

Why does that file have an emojiyhuh

slate swan
stoic galleon
#
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at /home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py:416> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn name: String value did not match validation regex.')>
Traceback (most recent call last):
  File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py", line 492, in sync_all_commands
    raise ex
  File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord_slash/client.py", line 472, in sync_all_commands
    existing_cmds = await self.req.put_slash_commands(
  File "/home/runner/Vora-Bot-v10/venv/lib/python3.8/site-packages/discord/http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: String value did not match validation regex.

I get this error when i start up bot what should i do?

slate swan
#

why are you even using discord_slash

stoic galleon
#

because, i want it to be easier to use commands, slash is easier anyways

sick birch
#

So just use one of the forks?

slate swan
#

bro main has slash commands?

sick birch
#

There's no reason to be using crappy third party libraries

slate swan
#

disnakes impl is pretty easy

pliant gulch
#

Whether or not he uses main or discord_slash right now the issue is that the command name doesn't match the regex required

sick birch
#

True. You have an invalid slash command name

slate swan
stoic galleon
#

how do i use the main discord slash instead of third party?

sick birch
#

Read up on the docs

#

And the gist has some exmaples

stoic galleon
slate swan
#

Alr alr sorry dont use !ot😭

slate swan
#

😭😭😭

#

Clicked on it tooπŸ’€ i thought it was real

#

i didnt!

slate swan
slate swan
pliant gulch
# stoic galleon how do i find out which one doesnt match?

"CHAT_INPUT command names and command option names must match the following regex ^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ with the unicode flag set. If there is a lowercase variant of any letters used, you must use those. Characters with no lowercase variants and/or uncased letters are still allowed. USER and MESSAGE commands may be mixed case and can include spaces." (https://discord.com/developers/docs/interactions/application-commands#application-command-object)

Discord Developer Portal

Integrate your service with Discord β€” whether it's a bot or a game or whatever your wildest imagination can come up with.

verbal breach
torn sail
#

I tried to do that and I couldn’t. I’m not sure if it’s possible

verbal breach
#

a phrase said when something goes wrong.

#

i drop a vase.c”

#

”oop”

supple thorn
slate swan
verbal breach
#

oop…..

slate swan
#

its a term which means Object Oriented Programming

hoary cargo
#

I dropped a vase, object oriented programming, damn it

slate swan
#

πŸ˜”

pliant gulch
#

Waiting for reactive paradigm to get super popular

slate swan
#

dont even know about it bro bless me with knowledge

pliant gulch
#

To really simplify it, it's event driven programming

slate swan
#

huhrooPopcorn

pliant gulch
#
Red Hat Developer

Reactive, what an overloaded word. Many things turn out to become magically Reactive these days. In this post, we are going to talk about Reactive Programming, i.e. a development model structured around asynchronous data streams.

I know you are impatient to write your first reactive application, but before doing it, there are a couple of things...

final iron
#

Make some true and make some false

#

πŸ€·β€β™‚οΈ

somber sky
#

Does anyone know how to make it where once you hit 20 the command stops working. Its pretty much a cap command max players on a team is 20 i wanna make it where once u hit 20 the command wont do anything.

final iron
#

Just spit balling but what happens if you do true, false, true, false

#

Yeah I'm out of ideas then

sick birch
left crater
#

you can use while

sick birch
#

Not really. It's not a loop

potent otter
#

Having an issue where error states
discord.errors.ClientException: ffmpeg was not found.

FFmpeg is imported, with PyNaCl.

 with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
          info = ydl.extract_info(url, download=False)
          url2 = info['formats'][0]['url']  
          voice_channel = ctx.author.voice.channel
          source = await discord.FFmpegOpusAudio.from_probe(url2,**FFMPEG_OPTIONS)
          vc.play(source)
sick birch
#

We can't help with that, it's against Youtube's terms of service

potent otter
#

Ah, they shut it down?

sick birch
#

What, ffmpeg?

potent otter
#

Yeah, I was watching tutorial on Youtube for a music bot

sick birch
#

Makes sense. Don't get into the habit of watching youtube tutorials

potent otter
#

lol

sick birch
#

And streaming audio from youtube outside of youtube is in violation of their terms of service and is a surefire way to get your bot a cease and desist order

potent otter
#

I'll see if I can subsitute youtube with spotify

sick birch
#

Doubt

#

Their API doesn't allow you to do that afaik

final iron
potent otter
#

mann

sick birch
#

Most platforms don't want you streaming music from them since they can't get the ad revenue

#

That's not to say there aren't any, it's just harder to find

potent otter
#

Yeah I understand

sick birch
#

One of the reason there's a shocking lack of music bots on discord these days

lament mesa
#

A solution for that is singing your own music and playing it

#

I have tried that once πŸ˜…

slate swan
slate swan
gentle wren
#

I'm Scared

slate swan
#

if your address got leaked why are you leaking it again bro

#

and you should disconnect your router for about a day so your isp cycles ips or just contact them so they will change it

#

they will still know were you live but they cant ddos since your public ip was changed

boreal osprey
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord' has no attribute 'author'```
#

i keep getting this error

slate swan
#

the module doesnt have that attr

boreal osprey
# sick birch Let's see your code
@bot.command()
async def suggest(ctx, *, message):
    channel = bot.get_channel(958144429821132814)

    author = ctx.author

    await ctx.message.delete()
    e=discord.Embed(title="Suggestion", description=message, color = discord.author.color)
    e.set_footer(text=f"suggested by {ctx.author.name}#{ctx.author.discriminator} | ⬆️ upvote | ⬇️ downvote | ❌ disapproved | βœ… next video | ❎ already done")
    e.set_author(name=ctx.message.author, url=ctx.author.avatar_url)
    message = await ctx.send(embed=e)
sick birch
slate swan
sick birch
#

Should be ctx.author

#

Also instead of doing f"{ctx.author.name}#{ctx.author.discriminator}", you can just do f"{ctx.author}"

boreal osprey
sick birch
#

Yes. Usually the errors are pretty descriptive

slate swan
#

but only smort people like me can know the real issue

#

not even a helper espFacepalm

#

how can I mention a member

sick birch
slate swan
sick birch
#

Yes. It's .mention

slate swan
#

I am using that

sick birch
#

The error says otherwise

slate swan
sick birch
#

You're doing .username

#

Just like the error says

slate swan
# slate swan

and you could just use or so no need for the if statement

#

member = member or ctx.author

sick birch
#

Again, I can't reiterate the fact that errors in python are VERY clear and they can lead you to the exact source of the error if you know how to read them

slate swan
#

so where is my oproblem

#

bro

sick birch
#

Just as the code said

#

"Member has no attribute username"

slate swan
#

message.author returns a member object!

sick birch
#

see?

slate swan
#

which the attr isnt even needed as Context already has the author attr!

sick birch
#

aw it deletes it

slate swan
#

I confused myself

somber sky
#

RS = 21

`{len([member for member in role.members])}/{RS}`

if {len([member for member in role.members])} > {RS}:
await ctx.send(f"test")``` 

im trying to make it where once the role.members hits the RS (21) then it sends "test"
slate swan
#

why are you iterating role.members to make it a list if it already returns a list?

somber sky
#

it doesnt return a list

slate swan
#

!d discord.Role.members

unkempt canyonBOT
slate swan
silent ermine
slate swan
#

weird

somber sky
#

it does this

pliant gulch
#

!e ```py
import difflib

class Example:
def init(self) -> None:
self.bar = "bar"
self.baz = "baz"

def __getattr__(self, attribute: str) -> "Any":
    try:
        return super().__getattribute__(attribute)
    except AttributeError:
        close = difflib.get_close_matches(attribute, self.__dict__)
        raise AttributeError(f"{self.__class__!r} object has no attribute `{attribute}`. Did you mean `{close}`")

Example().bar
Example().baz
Example().bat

unkempt canyonBOT
#

@pliant gulch :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 11, in __getattr__
003 | AttributeError: 'Example' object has no attribute 'bat'
004 | 
005 | During handling of the above exception, another exception occurred:
006 | 
007 | Traceback (most recent call last):
008 |   File "<string>", line 18, in <module>
009 |   File "<string>", line 14, in __getattr__
010 | AttributeError: <class '__main__.Example'> object has no attribute `bat`. Did you mean `['baz', 'bar']`. Did you mean: 'bar'?
pliant gulch
silent ermine
sick birch
slate swan
silent ermine
silent ermine
silent ermine
pliant gulch
slate swan
silent ermine
silent ermine
slate swan
#

attribute

silent ermine
unkempt canyonBOT
#

disnake/role.py lines 361 to 369

@property
def members(self) -> List[Member]:
    """List[:class:`​Member`​]: Returns all the members with this role."""
    all_members = self.guild.members
    if self.is_default():
        return all_members

    role_id = self.id
    return [member for member in all_members if member._roles.has(role_id)]```
slate swan
#

bro its a list

#

the return type is a list so it wouldnt return None or any other type

silent ermine
#

how to make something like @commands.has_perms
is is like @bot.check

slate swan
silent ermine
slate swan
silent ermine
#

Something like that?

slate swan
#

!d discord.ext.commands.Bot.check

unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").

Example...
slate swan
#

This function can either be a regular function or a coroutine.

silent ermine
pliant gulch
#

You need to specifiy in your function signature that it takes Context

slate swan
#

theres examples in docs!

silent ermine
slate swan
silent ermine
#

Huh pretty simple

slate swan
#

Context already has the attr

#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
#

ctx.author.name

#

I typed it wrong mb

#

I meant that yeah

#

how couldve you typed a whole phrase wrongAG_KannaHuh

#

when I run the command it isn't saying the correct key value for my json file though

#

just index the key correctly for the right value

#

I have it like this

#

{"y9su#8009": 1}

#

but it's saying I have 0 points

pliant gulch
#

ctx.author.name doesn't include the discriminator

slow estuary
#

do discord bots in pythons still work?

pliant gulch
#

Either way, I would suggest storing the USER ID, not the username and discriminator.

slate swan
#

well you dont have points and you shouldnt use tags anyways

pliant gulch
#

They can change names, etc. While IDs cannot

keen lynx
#

getting ratelimted pop on terminal after launching bot WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 58.99 seconds tho bot's working fine, able to use command while ratelimited. i guess bot does not when its get rate limited. this WARNING pop up every minute.
i dont know whats wrongπŸ˜‘

slate swan
#

if I use ID's how would I be able to ping for a user to check there points

pliant gulch
#

<@id>

slate swan
#

Ahh

slate swan
silent ermine
slow estuary
#

mine completely broke for some reason a few weeks ago

slate swan
slow estuary
#

it logs on fine but it doesnt pick up any messages and sends nothing

slate swan
slate swan
wispy spade
slate swan
slow estuary
#

like having multipe if in message. contain?

slate swan
#

what

wispy spade
slate swan
slate swan
#

it doesnt

#

what does it show

#

bro

#

it literally says it your discord name!

pliant gulch
#

Cast the user object to str to get user#tag or name + discriminator

slate swan
#

discord name is username and tag

unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
slate swan
#

only the username and not the discriminator

#

Ok then, what shows both?

slow estuary
#

so the await bot.process_commands(message) would go on the same indent outside of the brackets?

slate swan
unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

just use this deco

slate swan
unkempt canyonBOT
#

discord/member.py lines 361 to 362

def __str__(self) -> str:
    return str(self._user)```
slate swan
#

bro

#

im on to many drugs for this I swear 😭

slow estuary
silent ermine
slate swan
#

what the fuck is dunder

#

bro

#

__str__ __init__etc are dunders or special methods

slate swan
slow estuary
slate swan
slow estuary
#

oops lemme fix that

#

sorry

slate swan
#

not a problem

#

ctx.author.discriminator gets only the tag right

#

yes

#

!d discord.Member.discriminator

unkempt canyonBOT
#

property discriminator```
Equivalent to [`User.discriminator`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.discriminator "discord.User.discriminator")
slate swan
#

so if I use both it would get both?

#

bro

#

yes but you already been told casting the obj into a string already returns both?

slate swan
slow estuary
#

what what would it be defined as user?

slate swan
slate swan
slate swan
slate swan
slate swan
slow estuary
#

i feel like im doing something wrong

slate swan
slate swan
slate swan
slow estuary
#

the messages are under a client event, which are the events I'm trying to fix

slate swan
slate swan
slow estuary
supple thorn
slate swan
# slate swan rewrite this with smaller words (easier to understand)

ok ok str(obj) converts a object/class into a string which the string dunder/special method is responsible to return a value when the class is casted into a string which since your obj and attrs are in a f string no need to so just add the Context class and the author attr ( ctx.author ) which it would just cast the Member obj since the author attr returns a Member obj into a string which i earlier showed the string dunder/special method of the member class.

slate swan
#

???

supple thorn
#

lmao knew it

slate swan
supple thorn
#

the first one okimii said was more simplier

slate swan
supple thorn
slate swan
#

pls learn oop and basic pythonπŸ˜”

slate swan
supple thorn
#

oh it is?

slate swan
#

yeah in xey code

supple thorn
#

should of read more