#discord-bots

1 messages · Page 988 of 1

maiden fable
#

No

lofty pecan
#

ho okay

maiden fable
#

It has to be the event deco

slate swan
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

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

oki oki

slate swan
#
@client.event
async def on_message(message):
  if message.author.id in blacklist:
    return
  await bot.process_commands(message)

looks cleaner still

#

Gg

slate swan
lofty pecan
#

yay it works now

slate swan
#

0.01 byte space

exotic kite
#

guys how can i make the code that when my bot joins or leaves a server it tells me in a channel like this
I was invited to Server name.

maiden fable
slate swan
lofty pecan
#

thanks hunter

exotic kite
slate swan
maiden fable
exotic kite
slate swan
maiden fable
maiden fable
slate swan
#
@bot.event
async def on_guild_join(guild):
     channel = await bot.fetch_channel(id)
     await channel.send(f"Joined {guild.name}")
slate swan
exotic kite
maiden fable
maiden fable
slate swan
#

;-;

exotic kite
#

dead chat

#

dont chat

#

dead chat, dont chat

#

tbh so true

slate swan
maiden fable
#

@slate swan there's a reason we don't give away code (spoonfeed) but help them understand it.
If they want the code directly, they can always go to Stack

#

!d discord @slate swan

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

slate swan
#

F

brisk zodiac
#
import os
from discord.ext import commands
from random import randrange

number = randrange(100)
number2 = randrange(100)
answer = number2 + number

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

@client.command()
async def math(ctx):
    await ctx.channel.send(number number2)
    if answer == True:
        await ctx.send('True')

@client.event
async def on_ready():
    print('Yo My Creator')

client.run(os.getenv('TOKEN'))```I'm trying to make the bot to send an expression and when user send the correct answer it says "True"
slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

brisk zodiac
#

okay

exotic kite
#

@slate swan what do i do with this

@bot.event
async def on_guild_leave(guild):
      channel = await bot.fetch_channel(id)
      await channel.send(f"I left {guild.name}")```
slate swan
#

Bruh

brisk zodiac
slate swan
brisk zodiac
#

okay

exotic kite
#
@bot.event
async def on_guild_leave(guild):
      channel = await bot.fetch_channel(id)
      await channel.send(f"I left {guild.name}")```

it wont send that it left the server
slate swan
#

Did u literally put id in the code

exotic kite
#

yes

slate swan
#

I suggest learning python first

exotic kite
#

bro ik- im just not used with bot events

slate swan
#

show ur code that u have put

slate swan
#

Same?

#

Did u define id?

exotic kite
#

@bot.event
async def on_guild_leave(guild):
channel = await bot.fetch_channel(966361477055414374)
await channel.send(f"I left{guild.name}")

#

this

slate swan
#

whats the error

exotic kite
#

it wont send it

#

no errors, it will send when join

slate swan
#

Did u enable the intents

quaint epoch
#

bruv

#

on_guild_leave isn't an event

#

on_guild_remove is tho

exotic kite
slate swan
#

uh

flat solstice
#

random question, can someone send me some articles/docs related to mapping data type? What I've read is related to the map() function and says that the func takes another func and some form of iterables as params however that isn't how the Type: of discord.AutoShardedClient.shards seems to say
https://discordpy.readthedocs.io/en/master/api.html#discord.AutoShardedClient.shards
Is this returning a list or a dict or something else (a mapping data type that I've never heard of perhaps)

brisk zodiac
#

What should I do to fix this?
File "/Users/hungdinh/mu_code/Learn Python.py", line 24
await ctx.send(number number2)
^
SyntaxError: invalid syntax

slate swan
#

bru

quaint epoch
#

show all the code

#

well, up to teh 24 lines

slate swan
#

Ig he is starting from dpy

quaint epoch
#

await ctx.send(f'{number}{number2}')

sick birch
slate swan
#

..

exotic kite
#

choice

sick birch
#

Sure but we want to avoid it as much as possible here

slate swan
#

Sry

boreal ravine
#

you don't learn much from getting spoonfeeded

sick birch
#

And they come back later and bother us with similar questions because they didn’t learn anything the last time

slate swan
#

..

boreal ravine
slate swan
#

Yes

frozen patio
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

frozen patio
#

We cannot help with music.

vale wing
#

ytdl music*

frozen patio
#

What are you trying to loop?

vale wing
#

And other illegal streamers

vale wing
frozen patio
#

I made my own

#

With loop and stuff

#

I used ytdl sadly

#

😔

vale wing
#

@slate swan I can only give one clue and it is infinite recursion

#

😀 👍

vale wing
frozen patio
#

Yea

#

I had some errors, but I debugged them myself

vale wing
#

Nothing else sorry

#

Unless you'd make a bot that would play music files

slate swan
#

I hope music comeback to discord

vale wing
#

Imagine discord making their own music service inside of discord

slate swan
#

I dont think they will

vale wing
#

Just like they made timeouts and threads - destroyed most of "simple moderation" and tickets bots correspondingly

#

Now only advanced ones remained useful

silver wolf
#

Weren’t they suppose to force all bots to go to slash commands this month?

frozen patio
#

Only verified ones

vale wing
#

Message content intent will be restricted after aug 30 won't it?

frozen patio
#

Yea

silver wolf
maiden fable
frozen patio
#

75 to 100 yes

spice folio
#

anyone know how to make a / command?

frozen patio
#

Yes I do!

#
@bot.slash_command(title="Hi", description="Hello")
async def hicmd(inter: Interaction):
    await inter.send("Hello there.")
#

I think that is right

vale wing
#

Depends with what library

slate swan
frozen patio
#

I did this in nextcord

vale wing
#

With dpy it is different (and bad imo)

frozen patio
#

and in disnake it is different

#

I like nextcord the best

vale wing
#

Almost the same afaik

silver wolf
vale wing
silver wolf
#

Ohh. Ok thx

maiden fable
frozen patio
cobalt jacinth
#

how to resolve it

vale wing
#

Wth

#

Bots having such error?!

#

Imagine 2fa for bots

maiden fable
slate swan
frozen patio
#

He might need 2 Factor Authentification

cobalt jacinth
#

ok i need it

frozen patio
#

Yea

slate swan
# spice folio anyone know how to make a / command?

SLASH COMMANDS WITH DISCORD.PY

from discord.ext import commands
from discord import app_commands

bot = commands.Bot(command_prefix="?", intents=discord.Intents.default())

@bot.tree.command(name="ping")
async def Ping(interaction: discord.Interaction) -> None:
  await interaction.response.send_message("Pong!")

SLASH COMMANDS FOR DISNAKE (change disnake to nextcord for nextcord)

import disnake
from disnake.ext import commands

bot = commands.Bot(intents=disnake.Intents.default())

@bot.slash_command()
async def ping(inter: disnake.CommandInteraction):
  await inter.response.send_message("Pong!")
vale wing
#

The bot?

slate swan
frozen patio
#

Yea he doesn't use it

spice folio
#

i use replit

frozen patio
#

Oh god

spice folio
#

lol

frozen patio
slate swan
silver wolf
frozen patio
#

Spoonfeeding today 🙂

slate swan
#

Yes

vale wing
slate swan
#

Ash must have a blog website

spice folio
frozen patio
#

People ask for my code and I send a rickroll to them 🤣

slate swan
#

Lol

slate swan
silver wolf
vale wing
#

I send one of my projects so they can have "code"

frozen patio
#

I send rickrolls

#

They leave me alone after that

slate swan
frozen patio
#

🙂

maiden fable
slate swan
#

hunter knows everything

frozen patio
#

Yes

slate swan
#

lmao

maiden fable
maiden fable
frozen patio
#

Should be Helper Yes

slate swan
frozen patio
#

It's sadly not up to us 😔

silver wolf
slate swan
#

😔

#

Back

frozen patio
#

Ok

slate swan
#

..

frozen patio
#

Nice

#

I was today year's old when I learned that.

slate swan
#

lmao

maiden fable
#

Tho I saw the edit and the message, no need to delete it

frozen patio
#

I am not 20

slate swan
frozen patio
#

xD

slate swan
frozen patio
#

Lower

maiden fable
#

Take this to an OT

slate swan
#

Todays date is 20

frozen patio
#

Oh

paper sluice
frozen patio
#

Ye it is

slate swan
frozen patio
#

I got a ping from an OT channel

frozen patio
slate swan
#

Same

slate swan
#

Confirm

frozen patio
#

No

halcyon bison
#

how do i make my bots status on DND

frozen patio
#

Change it in the on_ready statement

slate swan
#

He mean" how do i change"

cloud dawn
frozen patio
#

Mmmm

#

Then idk

cloud dawn
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

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

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

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
halcyon bison
#

no

#

status=discord.Status.idle)

#

i dunno what to put here

#

for it to be DND

#

hey sparky

slate swan
#

Yo

halcyon bison
#

oh waistatus=discord.Status.idle)

#

frick

slate swan
#

but will the db variable become a bot variable?

halcyon bison
slate swan
#

uh?

paper sluice
#

F

slate swan
paper sluice
#

K

slate swan
#

huh wtf?

halcyon bison
#

!d discord.Status

unkempt canyonBOT
#

class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") ‘s status.
halcyon bison
#

nuu

slate swan
#

hm, so if I use it in my cogs like

#all the cogs stuff
def __init__(self, bot):
  self.bot = bot
  self.bot.db

would it work though?

#

I do know about the attributes

slate swan
#

hm tysm yerl and ryuga

slate swan
#

bot.change_presence(status=discord.Status.idle)

cloud dawn
slate swan
slate swan
#

Haven’t touched python in over a year so I’m a little confused

cloud dawn
cloud dawn
cloud dawn
# slate swan conclusion?

The best is to use subclassing, if you don't use that define the var in the place where you also define your client/bot

slate swan
#

Lmao

#

..

paper sluice
#

..

slate swan
#

Wow which lib for music

cloud dawn
#

I meant a Client/ Bot object not a Cog

#

Yep scrolled a bit up, still why was he/she confused when I asked about the subclassing

paper sluice
#

Bot-instance.var

cloud dawn
#

I got 3 vars in the init and other I set inside the setup hook

#
from datetime import datetime

import discord
from aiohttp import ClientSession
from discord import Client, Intents

from constants import config
from ext.backend.error_handler import CmdTree
from log import log

from ext.utils import Core, Fnine


class Dispy(Client):
    https_session: ClientSession

    def __init__(self) -> None:
        self.owner_id = int(config.bot.owner_id)
        super().__init__(
            intents=Intents(),
            application_id=config.bot.app_id,
            owner_id=self.owner_id
        )
        self.launch_time = datetime.now()
        self.tree = CmdTree(self)

    async def setup_hook(self) -> None:
        self.https_session = ClientSession()

        self.tree.add_command(Core(), guild=discord.Object(id=config.debug.guild))
        self.tree.add_command(Fnine(), guild=discord.Object(id=config.debug.guild))
        await self.tree.sync(guild=discord.Object(id=config.debug.guild))
        if config.debug.global_cmds:
            await self.tree.sync()

    async def close(self) -> None:
        await self.https_session.close()
        await super().close()

    @staticmethod
    async def on_ready() -> None:
        log.info("Ready")
#

Yean nothing much, I'm only going to add a database object to this.

#

I used an async hack before with event loop but setup hook is a game changer.

#

And I need a custom solution to add my own cogs since Client doesn't have cogs :/

paper sluice
#
bot = ur bot
async with bot:
  async with database...:
    bot.var = ...
    bot.start() 

If ur db Conn can be used as a cm

cloud dawn
#

Disnake has a setup func?

#

Not that hard tbh I'm just going to code it myself since i really don't want the bot to have a message prefix.

#

I can see why they didn't like that lol

#

I'm actually pretty close.

#
        if module.ispkg:
            imported = importlib.import_module(module.name)
            for name, obj in inspect.getmembers(imported):
                if inspect.isclass(obj) and issubclass(obj, Group):
#

Checking if subclassed item is Group, if it is Group it contains my slash commands.

#

I still need a way to call those classes and have it return it all recursively.

#

It's pretty gut

#

For this case then

#

Tbh I didn't knew it first I would like it more if they added it to inspect.

#

Way ahead of you lol

#

I checked it out but the only reason they have a setup func is to pass bot

#

And to have a more genuine check.

#
import importlib
import inspect
import pkgutil

from typing import Iterator, NoReturn

import ext
from discord.app_commands import Group


def unqualify(name: str) -> str:
    """Return an unqualified name given a qualified module/package `name`."""
    return name.rsplit(".", maxsplit=1)[-1]


def walk_extensions() -> Iterator[str]:
    """Yield extension names from the exts subpackage."""

    def on_error(err_name: str) -> NoReturn:
        raise ImportError(name=err_name)  # pragma: no cover

    for module in pkgutil.walk_packages(ext.__path__, f"{ext.__name__}.", onerror=on_error):
        if unqualify(module.name).startswith("_"):
            # Ignore module/package names starting with an underscore.
            continue

        if module.ispkg:
            imported = importlib.import_module(module.name)
            for name, obj in inspect.getmembers(imported):
                if inspect.isclass(obj) and issubclass(obj, Group):
                    # https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/bot.py#L899
                    # obj.__name__
                    yield obj


EXTENSIONS = frozenset(walk_extensions())

``` using this rn but it isn't finished, i got distracted making commands first lol
#

@slate swan Do you got a bot?

#

Can relate.

#

Back-end is just too fun.

#

Nothing you need relative imports.

slate swan
#

how to make a bot that will ban any one who says something is unfunny on sight

sick birch
slate swan
#

then How Do i GIVE THEM a sense of umor

sick birch
#

I would hope you don't

slate swan
#

I would LIKE TO SHARE MY sense of tumor to the world

sick birch
#

A computer with a sense of humour is terrifying

#

But to answer your questions, you would need to train a machine learning model

slate swan
sick birch
#

Have an API interact with said machine learning model, and using an on_message() event you can query the model for a positive/negative result and action based on that

cold sonnet
paper sluice
oblique adder
#

What could be the benefit of using python instead of javascript for developing a bot?

cloud dawn
sick birch
cloud dawn
slate swan
#

The message won't update and i get no errors:

@tasks.loop(seconds=60)
async def lb():
  msg = await bot.get_channel(966068951626944522).fetch_message(966069258385756180)

  db = mysql.connector.connect(
    host="",
    user="",
    passwd="",
    database="")
  mycursor = db.cursor()

  mycursor.execute(f"SELECT * FROM logs_info")
  for i in mycursor:
    text = f"User: <@{i[1]}> | Tickets: {i[2]}"
  embed = discord.Embed(title=f"Middleman Logs", description=text, color=0x303135)
  embed.set_footer(text="This message will be updated every 1 min.")
  
  await msg.edit(embed=embed)```
#

do you start the loop?

slate swan
#

yep

#

and it should be in my on_ready?

#

iy can be anywhere

#

*it

dull terrace
#

itll show the time if you hover over the edited thing (test edit)

slate swan
dull terrace
#

also, if you're using the same message for it every time, you should just fetch it once as a global to lower api calls...

#

not entirely sure why it wouldn't edit though, it can't be actually looping and going over the code? print something and see if it prints every minute

slate swan
#

okay]

#

nothing prints

#

Yo

#

Can anyone suggest how do i make like 30min 1h and 1w

#

In giveaway

quaint epoch
#

but ig if you want asyncio.sleep works

#

but don't sleep for 10 days at a time lol

slate swan
#

Ok..

sacred oyster
#

why fails?

opal cosmos
#

why wont this welcome message work?

@bot.listen()
async def on_member_join(ctx, *, member: discord.Member):
  await member.send("Welcome to the server!")
sacred oyster
#

member.send?

opal cosmos
#

dms the person

sacred oyster
#

ah ok

#

what's the error log?

quaint epoch
# sacred oyster

it needs positional args, like content='', image=discord.File etc

opal cosmos
sacred oyster
quaint epoch
#

and also turning it into a kwarg is unneccesary

opal cosmos
#

u mean typehinting?

quaint epoch
#

send line 38 in coinflip

quaint epoch
#

i don't think listeners work outside of cogs

sacred oyster
quaint epoch
quaint epoch
quaint epoch
opal cosmos
sacred oyster
quaint epoch
quaint epoch
cold sonnet
#

wow you really use content as a kwarg

#

😔

spice adder
#

Is there a good way to ensure I don't run into error 429 or too many requests?

quaint epoch
cold sonnet
#

love u

opal cosmos
quaint epoch
spice adder
#

No, modmail

quaint epoch
opal cosmos
#
@bot.event
async def on_member_join(ctx, member: discord.Member):
  await member.send("Welcome to the server!")
quaint epoch
#

!d disnake.on_member_join

spice adder
#

Last night I left the bot idling. It pretty much just sends ban logs and handles mod mail, but it still ran into the error for some reason

unkempt canyonBOT
#

disnake.on_member_join(member)``````py

disnake.on_member_remove(member)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") leaves or joins a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").

This requires [`Intents.members`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.members "disnake.Intents.members") to be enabled.
quaint epoch
#

hmmm

#

oh yes, don't pass in ctx

#

it's an event, not a command

#

brainmon forgot

#
@bot.event
async def on_member_join(member: discord.Member):
  await member.send("Welcome to the server!")```
opal cosmos
#

still no message

quaint epoch
#

really?

#

what version are you running?

opal cosmos
#

mhm

#

how do i check that again

wise kettle
#

@opal cosmos have you enabled member intents for your bot?

opal cosmos
#

XD

#

thats prob it

spice adder
olive osprey
flat solstice
#

why is this line producing this error?py Ignoring exception in on_voice_state_update Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event await coro(*args, **kwargs) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 270, in on_voice_state_update f"Requested to speak: <t:{int(after.requested_to_speak_at)}:R>", TypeError: int() argument must be a string, a bytes-like object or a real number, not 'datetime.datetime'I tried wrapping it in a str() but it didn't like it

full lily
#

you need to convert that datetime object to an epoch

flat solstice
#

is that as possible as adding .timestamp to it?

full lily
#

yes

flat solstice
#

oh cool, I'd removed that bc it had been giving me errors before (about a week ago is when I last touched it so I can't remember the error)

#

but hey it's working now

opal cosmos
#

ok it says that i need to add a redirect uri on my developer portal when im creating an invite link but there are no options listed, what do i do

olive osprey
# junior verge Code?

It's a pretty long one, but I already figured it out with some friends^^ Thank you anyways.
It's most likely a caching problems, as it just doesn't work in a specific channel

wise kettle
#

is the built-in help() command expected to work in private channels? I'm getting an exception Command raised an exception: AttributeError: 'Object' object has no attribute 'send' when I use it in a DM. Works as intended in the server.

slate swan
#

hello i want the bot to read response

silent portal
#

Why can't I import EmptyEmbed ?

slate swan
#

ive made verify with random string and i wanna read response

opal cosmos
#

can member.kick not be used in an await expression?

#

bcs my error says it cant

full lily
full lily
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

full lily
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). 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.10)") 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.10)") 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**...
opal cosmos
full lily
#

if you click into this, they have some good examples

full lily
opal cosmos
# full lily traceback. The big error message
Ignoring exception in command kick:
Traceback (most recent call last):
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/Delta/mod.py", line 19, in kick
    await self.bot.kick(member)
AttributeError: 'Bot' object h
Ignoring exception in command kick:
Traceback (most recent call last):
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/Delta/mod.py", line 19, in kick
    await member.kick
TypeError: object method can't be used in 'await' expression

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

Traceback (most recent call last):
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/Delta/venv/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: object method can't be used in 'await' expression
full lily
#

await member.kick()

#

are you missing brackets there?

opal cosmos
#

yeah

#

thx it works now

#

also, my bot still wont send custom emojis

#

<:name_here:id_here>

#

thats right format right?

slate swan
#
@bot.event
async def on_member_join(message):
  await message.send(f"reply to this message with key: ||{key}||")
    m = await bot.wait_for('message', timeout=60.0, check=check)
    if m.content == key :
        memberr = message.author
        await bot.add_roles(memberr, roll)
        await message.send('Role added')
    else:
        await message.send('Incorrect key')
``` i cant seem to get dm from bot
#

everything is defined

olive osprey
olive osprey
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

Can we deploy a hangout(google chat) chatbot for free?

slate swan
#

wym

slate swan
plain knoll
olive osprey
slate swan
#

but yes argument naming is important.

olive osprey
#

^

olive osprey
plain knoll
#

Okay

slate swan
#
@bot.event
async def on_member_join(message):
  await message.send(f"reply to this message with key: ||{key}||")
  def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
m = await bot.wait_for('message', timeout=60.0, check=check)
  if m.content == key :
        memberr = message.author
        await bot.add_roles(memberr, roll)
        await message.send('Role added')
  else:
        await message.send('Incorrect key')``` bot wont read key
olive osprey
#

Where's key defined?

slate swan
wise kettle
#

You are waiting for a "message", but your check() function is checking for a reaction. check will always evaluate to False and it will not parse your message

junior verge
#

You aren't defining key

torn sail
slate swan
slate swan
#

i was thinking of another bot

silver wolf
#

So I made a cog with slash commands using app_commands

@app_commands.command()
async def test(self, inter: discord.Interaction):
    ...

And I have a normal sync command

@commands.command()
@commands.is_owner()
async def sync(self, ctx: Context):
     await self.bot.tree.sync(guild=discord.Object(id=305912183189929984))
     await ctx.send("Slash commands synced")

But when it's synced the slash commands dont show up

slate swan
#
@bot.event
async def on_member_join(message):
  await message.send(f"reply to this message with key: ||{key}||")
  m = await bot.wait_for('message', check=lambda message: message.author)
  if m.content == key :
    memberr = message.author
    await bot.add_roles(memberr, roll)
    await message.send('Role added')
  else:
   await message.send('Incorrect key');```
slate swan
formal basin
#

How can I make this thing in economy were if you buy something it will give me money every somthing seconds e.g I buy I manager then the manager gives me money every 3 minutes

heady heron
#

hey, im trying to use slash commands now, but i keep getting a CTX error. Before my slash conversion, it worked fine though. Anyone know why?

chilly igloo
#

Can someone assist me with warn, mute, ban, kick and timeout commands?

frozen patio
#

you use inter instead

#

¯_(ツ)_/¯

heady heron
#

wat

#

whats inter?

#

do i just replace ctx with inter?

slate swan
#
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
    base.commit()
    print(1)
    
    warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
    print("работает")
    
    
    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if warnings is None:
        cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
        base.commit()
        print(2222)
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
    else:
        cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
        base.commit()
        await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")      

how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?

brave forge
#

how to pass several values through embed.set_image, namely, so that it randomly outputs one of 10 gif images
it's just that if you pass a variable where with the random module you get an error

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
brave forge
#

@boreal ravine I did it through it, it gave an error

boreal ravine
brave forge
#

@boreal ravine lmao how can it not be used properly ?

boreal ravine
brave forge
#

random.choice(['lol', 'kek'])

boreal ravine
#

that's not a url

brave forge
#

only instead of lol and kek there were links

boreal ravine
#

error?

brave forge
# boreal ravine error?

Command raised an exception: TypeError: set_image() takes 1 positional argument but 2 were given

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
brave forge
#

@boreal ravine what is the best way to use in order for the team to work a certain amount of time ?? Which module ??

#

@boreal ravine because when I was making buttons, people here told me that this module "import discord_components, Button, ButtonStyle from discord_components" was outdated

brave forge
boreal ravine
#

ah.

#

!d datetime ig

unkempt canyonBOT
#

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

spice adder
#

Not sure what I've got wrong with this:

@client.command()
async def test(ctx):
  await client.send("Test complete!")

@client.event
async def on_message(message):
    await modmail(message)
    await autopublish(message)
    await client.process_commands(message)
discord.ext.commands.errors.CommandNotFound: Command "test" is not found``` I've tried it both with and without ctx, and the reason why I'm using on message as I am is to allow for multiple on_message events
boreal ravine
spice adder
#

Yes

boreal ravine
spice adder
wise kettle
#

on_message() is a built-in function. Its default behavior calls process_commands() to tell the client to process commands. As you are overwriting on_message(), you need to add an await client.process_commands() at the end of your function

wise kettle
#

wow im blind.

flat solstice
#

is there a better way I could be structuring this f-string?py embed.add_field( name="Afk channel", value=f"{f'{before.afk_channel.mention}' if before.afk_channel is not None else None} -> {f'{after.afk_channel.mention}' if after.afk_channel is not None else None}", )

spice adder
#

Yeah it's just not finding the command for some reason

boreal ravine
#
before_channel = before.afk_channel.mention if before.afk_channel is not None else None
after_channel = after.afk_channel.mention if after.afk_channel.mention is not None else None

embed.add_field(
    name=...,
    value=f"{before_channel} -> {after_channel}"
)
pliant gulch
unkempt canyonBOT
#

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

None
pliant gulch
#

Instead of using a ternary condition you can just default a getattr

#

So you won't need that super long line

flat solstice
#

oh, that sounds intresting

#

since I have 4 of these really long statements so far

mellow mountain
#

So, i made three buttons with discord-components - now i want to check if the button is clicked by the executing user.. currently its possible that everyone is able to press these buttons.

Any idea?

embed.add_field(name="Your turn!", value="Choose whats happening now", inline=False), components = [
        [Button(label="less", style="4", emoji = None, custom_id="button1", disabled= False), Button(label="same", style="1", emoji = None, custom_id="button2", disabled= False),Button(label="higher", style="3", emoji = None, custom_id="button3", disabled= False)]
        ])

# [...]

interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1" or "button2" or "button3") # less
    if interaction.custom_id == ("button1"):
        await interaction.send(content = "You choose less.", ephemeral=False)
# do stuff
flat solstice
pliant gulch
#

I'd just do the getattr call

#

No reason to make a function for it

flat solstice
# pliant gulch I'd just do the getattr call

so something likepy embed.add_field(value=f"{getattr(before.afk_channel, "mention", None)} -> {getattr)after.afk_channel, "mention", None)}not sure if I'd followed you correctly

mellow mountain
boreal ravine
#

it should work

mellow mountain
#

Gimme a sec, i try that.

pliant gulch
#

Also your using double quotes inside of a string using double quotes

#

they need to be single quotes

flat solstice
scarlet sorrel
#

anyone know a better place to host discord bots that isn't replit or heroku because they both suck

mortal dove
#

All free bot hosting sucks

scarlet sorrel
#

alr

flat solstice
#

do filesize_limit and bitrate_limit update when a guild moves up a boost tier? and do those updates then call on_guild_update

idle laurel
#

with them backing up/ delaying. is this down to discord kinda limiting them or is it down to the code ?

umbral night
#

how do i fix this?

idle laurel
#

do you have them installed?

umbral night
#

it was working last night

#

when my friend helped me upload my stuff to github so he could help make my code cleaner

#

it like

#

stopped working

#

i forgot what i did with the folder, bc i was tired

flat solstice
#

did you have a virtual environment set up?

umbral night
#

yes

#

im not even sure how that works

#

my friend did it for me

umbral night
#

do you know how to fix it tho?

flat solstice
#

this env folder should be inside the folder where the rest of your code is

umbral night
#

it is

#

but uh ive noticed

#

my friend had me move those files to the folder that gets uploaded to github

#

its not in my vsc folder anymore

#

that could be why huh?

flat solstice
# umbral night that could be why huh?

yes and no,
yes that can be why it's not immediately picking up that the venv/env exists
but also no it won't stop you from accessing the venv/env

what does your file tree look like?

umbral night
#

file tree

flat solstice
#

yep

#

okay so what you want to do is cd into env

umbral night
#

so just cd env right

flat solstice
#

I take it your on linux?

umbral night
#

yes

flat solstice
#

okay so once your in the env directory you need to usebash bin/activate

spice adder
#

How do you get a message object from a message ID with a predefined channel?

flat solstice
flat solstice
flat solstice
#

weird

frozen patio
#

I like Windows

slate swan
#

windows is only good because its ui and its easy for users, i would try linux because its less heavy and it doesnt spy on you but i game sometimes (rarely)

pliant gulch
#

You should be doing . env/bin/active

umbral night
#

what

#

OH

#

YES IT WORKED

flat solstice
#
Ignoring exception in on_guild_update
Traceback (most recent call last):
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 129, in on_guild_update
    icon_url=after.owner.guild_avatar.url,
AttributeError: 'NoneType' object has no attribute 'guild_avatar'```not really sure what's going on here, as far as I can see `after.owner.guild_avatar.url` is a thing, using `on_guild_update` event
pliant gulch
#

Poetry is very very nice

umbral night
#

@pliant gulch

#

quack folder is actually empty

#

bc my friend made me move my stuff from quack to suede

#

@flat solstice ^??

flat solstice
#

is there a env folder in the suede folder?

umbral night
#

yes

#

but the vsc doesnt use the suede folder i dont think

flat solstice
#

okay then go up to file at the top menu of vsc, select open folder and then select the suede folder

umbral night
#

ohhhh

#

my env file didnt even upload

#
  File "/home/rore/suede/main.py", line 233, in <module>
    bot.run(TOKEN)
  File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 723, in run
    return future.result()
  File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "/home/rore/suede/env/lib/python3.9/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'

#

@flat solstice do i just make a new one?

flat solstice
umbral night
#

oh im stupid

#

ok thx

frozen patio
#

or if using slash

#

inter.guild.icon.url

flat solstice
flat solstice
#

think I got it, it was a intents issue

#

or at least giving my bot all intents fixed the issue

frozen patio
#

Ah

#

Yeah intents are becoming required

#

😅

polar ice
#

https://paste.pythondiscord.com/ebuzejefok The code ive got works perfectly and posts all the chat logs the first time the code executes. but then when the loop comes after 30 seconds it doesn't post. I've been advised that its re-using the same cursor and it i need to make it create a new cursor? Could anyone help me, i dont fully understand how to do it. Been stuck with this problem for a good 4 weeks now, id really appreciate any help 🙂

flat solstice
#

how could I check if the Guild.system_channel is different between before and after whilst also allowing for either before channel or after channel to be none?py async def channel_check(self, before, after): return f"{getattr(before, 'mention', None)} -> {getattr(after, 'mention', None)}" if before.system_channel.id is not after.system_channel.id: embed.add_field( name="System channel", value=await channel_check( self, before.system_channel, after.system_channel ), )because I'm currently gettingpy Ignoring exception in on_guild_update Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 375, in _run_event await coro(*args, **kwargs) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\events.py", line 167, in on_guild_update if before.system_channel.id is not after.system_channel.id: AttributeError: 'NoneType' object has no attribute 'id'if there is no system channel in before. Using on_guild_update

normal lark
#

hello can someone dm me to help me make my bot?

sick birch
unkempt canyonBOT
#

6. Do not post unapproved advertising.

normal lark
umbral night
#

what is this green stuff

#

it wont go away

sick birch
spice adder
#

What's the best way to get the message object with ID from another channel?

sick birch
#

Do you have that other channel's ID?

spice adder
#

Yes

sick birch
#

guild.get_channel(id).get_message(id)

umbral night
spice adder
sick birch
umbral night
#

oh

#

wait so do i have to update github

sick birch
#

And don't ask me how to turn it off lol

umbral night
#

or something

sick birch
#

Should be in vscode settings...

#

...somewhere

blissful sparrow
#

Erm so i have a tiny problem, Im trying to keep prefix commands and use app commands however the prefix ones stop working when the / ones are active, what would be a way to keep the command names the same for both command types?

mortal dove
#

Is there any way to make a view without making a class that inherts discord.ui.View? I need to access local vars in some of the view's elements' decorators.

mortal dove
wicked atlas
#

If you're trying to dynamically add items, you can use View.add_item()

red kernel
#

how do i make a autoresponder bot that responds with random messages to a key word like “no” or “yes”

blissful sparrow
supple thorn
blissful sparrow
mortal dove
red kernel
#

ok thanks freeflow

mortal dove
blissful sparrow
#

I am using 2.0, surprised I didnt see it tbh

#

it tells me this though

mortal dove
#

To install dev branch

#

aka hybrids

blissful sparrow
mortal dove
#

yup

#

btw, are you on windows?

#

@blissful sparrow

blissful sparrow
#

yeh

mortal dove
#

Press Win + Shift + S

#

For a select screenshot

blissful sparrow
#

ik, i use sharex

mortal dove
#

instead of caught lackin

#

oh okay

blissful sparrow
#

and custom host

slate swan
#

yo

#

UnboundLocalError: local variable 'json' referenced before assignment

#

show code

slate swan
#

how the fuc do i fix

#

!e

def a():
    print(b)
    b = 1
a()
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 |   File "<string>", line 2, in a
004 | UnboundLocalError: local variable 'b' referenced before assignment
slate swan
#

basic py

blissful sparrow
#

so I have a hybrid command that works twice then the third time says this interaction failed, is this due to ratelimit or something?

slate swan
#

no

#

its not due to ratelimitation

#

..

unkempt canyonBOT
#

Hey @normal lark!

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

normal lark
slate swan
#

we arent your interpreter so try it out and seeyert

normal lark
slate swan
#

why

normal lark
normal lark
# slate swan why

Do you know anything about the share bot tiktok because I've been trying to solve my problem for 2 weeks but I can't?

mortal dove
#

https://paste.ofcode.org/J4yWczLqdvUQNFYrWtNWgw Does anybody know why self.context is ... at this point? The point of this is to make a view with the options being the bot's cogs, and then when a cog is selected it sends the cog's send_cog_help method. At line 36.

slate swan
#

what library is that? discord.py ( if yes, be version specific )

#

and how do you invoke this command?

mortal dove
slate swan
mortal dove
boreal ravine
#

mention returns a string.. <@&267628507062992896> and you're comparing it to @deleted-role which is also a string but it isn't the same

#

idk

slate swan
#
if server.get_role(role_id):
  # role exists
else:
  # role does not exist```
#

heyo im trying to make a "boost count" command but im not rlly sure how the whole premium_tier thing works. someone able to explain it to me?

autumn trench
#

is it possible to get a list of a server's invite links?

frozen patio
#

I am trying to get the user name instead of the ID and remove the commas, and also list multiple people. What am I doing wrong?

slate swan
#

o

frozen patio
#

How can I get the user name of the top 5 highest ranked people in the server

#

You forgot a "

#

How would I do that 😅, I do not use indexs or loops.

#

I use nextcord

#

xD

#

I know how to use databases and such, but not indexes or loops. 😅

#

Nah

#

I am making my own

#

I could always

#

I will learn loops and stuff

slate swan
#

How can I fetch a role object?

#

From ID.

#

How can I make like the first command is ,setchan #1234
And then the bot uses the channel for the output of a particular channel

rain furnace
#

this is my code:

@bot.event
async def on_member_join(member, ctx):
  Dis = breakpoint.get_guild(config.guildID)
  embed = discord.Embed(colour=0x95efcc, description=f"Welcome to Nextvision! you are {Dis.member.count}", timestamp=datetime.datetime.utcfromtimestamp(1536229094))
  embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
  embed.set_author(name=f"{member.name}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
  embed.set_footer(text=f"{member.guild}", icon_url="https://cdn.discordapp.com/attachments/933768511145250896/966459729738076180/n7dCH2pmCcaFVWXB.gif")
  channel = bot.get_channel(id=962006966086025216)
  await channel.send(embed=embed)

I need to do welcome discord bot but its not working and there is no error

rain furnace
#

intents = discord.Intents.default()
intents.members = True
bot = discord.Client(intents=intents)

#

I have it

slate swan
#

Try do discord.Bot

#
bot = commands.Bot(command_prefix = bot_prefix, intents = intents)```
rain furnace
slate swan
#

Because you haven't defined it

#

what is your bot prefix

rain furnace
#

.

slate swan
#

then do this

#
bot = commands.Bot(command_prefix = '.', intents = intents)```
#

@rain furnace is intents turned on in your bot settings too?

rain furnace
#

I dont think so

sick birch
rain furnace
#

How I turnning it on?

sick birch
#

Let's not spoonfeed them

sick birch
#

There's nothing to be learned and I can see pretty clearly that they're just copy and pasting whatever you sent them without figuring out what does what or tweaking anything

slate swan
sick birch
#

Thank you for your understanding

slate swan
#

Ok, now my question.

#

How can I get a role object?
From ID.

rain furnace
slate swan
#

Does it work?

rain furnace
#

I am trying

slate swan
#

ok

sick birch
slate swan
#

Get.

#

I think i've just found the answer though.

sick birch
#

guild.get_role()?

#

And this is why I don't like stackoverflow

rain furnace
#

o

sick birch
#
from discord.utils import get

role_id = 123
role = get(guild.roles, id=role_id)

like why?

slate swan
#

Why what?

sick birch
#

Why would you use utils.get()

slate swan
sick birch
#

guild.get_role() is O(1) (due to hash map implementation) while utils.get() is definetely not constant time

rain furnace
slate swan
supple thorn
sick birch
#

obviously get_role

supple thorn
#

get_role or discord.utils.get? i'm assuming get_role

sick birch
#

hash map like i mentioned

#

I'm taking a stab at the dark and gonna say utils.get() is O(n^2)

supple thorn
#

yeah since utils.get loops through all roles

sick birch
#

Since it loops not only the provided iterable but also each attribute of each item in the iterable

supple thorn
#

yeah

rain furnace
sick birch
#

I'm pretty sure it might also allow nested attribute searching which could take it way above O(n^3) or some other exponential time complexity

supple thorn
#

i told someone to use get_role over someone who said to use discord.utils.get because i assumed get_role is faster

sick birch
#

Most, if not all, discord.py get_* methods are going to be the fastest

#

because most use a hash map

#

and we know hash map lookups are constant time

supple thorn
#

welp nice talking to you robin ima go back to fixing my wrapper's typehinting so mypy stops screaming

sick birch
#

yup. good luck

sick birch
unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

And what is breakpoint? The name of your bot instance?

rain furnace
#

no I am removing it I tried to do breakpoint because it didnt worked

sick birch
#

Removing what? What didn't work?

rain furnace
sick birch
#

Okay, what is breakpoint?

rain furnace
sick birch
#

That doesn't tell me much

rain furnace
#

I saw in youtube that many people using breakpoint for this line so I tried too

sick birch
#

That explains a lot of things

#

Did you also get ctx from that youtube video?

rain furnace
#

no i tried to do something else

#

but it didn't work

sick birch
#

Okay. First things first stop following some terrible youtube tutorial. They're usually always bad and give you code that won't work

rain furnace
#

ok

sick birch
#

Now, can you explain what you're trying to do so that I may assist you better?

rain furnace
#

Yes, I am trying to do welcome embed message

sick birch
#

Oh, that shouldn't be very hard

#

Just construct the embed within your on_member_join, determine a channel to send it to, and send using await ctx.send(embed=embed)

final iron
#

ctx in a on_member_join event?

sick birch
#

That's what I was thinking

boreal ravine
#

discordutils music awesome 😩

silver wolf
frozen patio
#

The error is user has no attribute to name. How can I fix this?

sick birch
#

Traceback please?

paper sluice
boreal ravine
slate swan
#

nvm its his variable naming that confused me

frozen patio
# sick birch Traceback please?
Ignoring exception in command lblevel:
Traceback (most recent call last):
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Student\Desktop\Ayrus\main.py", line 231, in lblevel
    embed.add_field(name=f"{user.name}", value=f"Level: {level[0]} | XP: {xp[0]}/100")
AttributeError: 'tuple' object has no attribute 'name'

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

Traceback (most recent call last):
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1048, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Student\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'name'
sick birch
#

Ah

slate swan
#

lol its not a user object

sick birch
#

await cursor.fetchone() returns a tuple

frozen patio
#

Ah

slate swan
#

yeah

sick birch
#

Default row factory...

slate swan
#

doesnt all rows lol

frozen patio
#

Do I need that line at all then?

sick birch
#

Set your connection to use aiosqlite.RowFactory

frozen patio
#

👀

#

Where?

sick birch
#

It provides things in a RowFactory object which has a lot more ways to access data

sick birch
frozen patio
#

Will that affect my other tables?

sick birch
#

It only affects the format in which data is returned to you

frozen patio
#

So it will

sick birch
#

I'm not all that much of a fan of sqlite/aiosqlite or any of the connnectors so I don't know much about it, I usually use ORMs

#

It won't affect your tables in the way that it alters the data

frozen patio
#

Okay

#

Is there a way to pull the data without altering the data at all?

sick birch
#

That's... how it's always done

frozen patio
#

I am just trying to get some data to loop in a leveling rank command

slate swan
#

it would be cool to have time comps in docs for disnake so i don't need to look up src code on mobile which is a pain

boreal ravine
frozen patio
#

What is this error mean?

boreal ravine
# frozen patio

You did ```py
@bot.command()
async def func(ctx):
pass

func[123]

frozen patio
#

Yes

boreal ravine
#

Yes

frozen patio
#

Oh

frozen patio
sick birch
#

Because functions aren't iterables

frozen patio
#

This is what I am doing

sick birch
#

You can only superscript, e.g use [] on iterables or classes that implement the __getitem__ method

echo wasp
#

hello i would like to know if something like this is possible py if message.author.id is not in users: code

sick birch
#

Actually that might throw a syntax error

echo wasp
#

fuction

sick birch
#

if message.author.id not in users works just fine

#

is is for comparing if 2 objects are the same, e.g True is True

echo wasp
#

right

sick birch
#

First line, role_name = role_name.split(":")

#

It doesn't know what role_name is so it can't split it

#

You can but you need to define the variable first

#

role_name = ... #something here

#

bot has no attribute emoji, and rightly so

#

Define role_name somehow

silver wolf
#

If ur trying to get the emoji the user sent, u have to access the content of the message

slate swan
#

How can I add a role to a user?

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

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

you can't add roles to a "user" but a "member"

sick birch
#

And yes, there is a difference

slate swan
#
    guild_ = client.get_guild(GUILD_ID)
    member = guild_.get_member(payload.user_id)
    role = guild_.get_role(962639887876632666)
    await member.add_roles(role) ```
Gives of a AttributeError: 'NoneType' object has no attribute 'add_roles' on the last line.
sick birch
#

Looks like it couldn't mind a member with that ID

slate swan
#

How?

slate swan
boreal ravine
slate swan
#

the time a computer takes to finish a task/algorithm

slate swan
#

😔

boreal ravine
#

Ah..

slate swan
slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

I have intents already.

#

show the lines where you define them?

#

My error has nothing to do with intents, @sick birch said before a completely different issue.

slate swan
#

ight then :)

silver wolf
slate swan
#

its an event

slate swan
slate swan
#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
sonic lintel
#

Hello

slate swan
# unkempt canyon

ill blame Danny for not mentioning tht it needs member intents to work

#

Full code is too long and the project isn't public.

sonic lintel
#

My bot is not responding to any commands, but appears to be online once I run it

#
import disnake
import os
from disnake.ext import commands,tasks
from disnake.ext.commands import has_permissions, CheckFailure

intents = disnake.Intents.all()
client = commands.Bot(command_prefix="m/", intents=intents)


@client.event
async def on_ready():
    print("Fun is online!")

@client.slash_command(name="test")
async def test(ctx):
    await ctx.send(content="Hello World!")

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please type in the full command.')

@client.command
async def check(ctx, member: disnake.Member = None): 
            em = disnake.Embed(colour=disnake.Colour.blue(),
                            title="**Middleman**")
            em.set_thumbnail(url=member.avatar_url)
            em.add_field(name="User Info:",
                        value="Id: User: ",
                        inline=False)
            em.add_field(name="Vouches",
                        value="`150+`",
                        inline=False)
            em.add_field(name="Servers:",
                        value="5",
                        inline=False)
            em.add_field(name="Started Middlemanning:",
                        value="`15th of June 2021`",
                        inline=False)
            em.add_field(name="Middleman Status:",
                        value="`Dm for middleman with a fee, no fee = block. Accepting non fee requests only in server requests.`",
                        inline=False)
            em.add_field(name="Fee status:",
                        value="Middleman takes fees ands tips.",
                        inline=False)
            em.set_footer(text=f"Requested by {ctx.author}")
            await ctx.send(embed=em)```
slate swan
#

!d discord.ext.commands.Bot.listen

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
slate swan
sonic lintel
#

HELP I JUST REALISED THAT LMAO

#

SO SORRY

slate swan
#

@client.command to @client.command ()

silver wolf
slate swan
#

as for your slash commands, they take 1hr to register if they didnt appear yet

sonic lintel
#

@client.event()
TypeError: event() missing 1 required positional argument: 'coro'

sick birch
slate swan
#

AttributeError: 'NoneType' object has no attribute 'add_roles'

    guild_ = client.get_guild(GUILD_ID)
    member = guild_.get_member(payload.user_id)
    role = guild_.get_role(962639887876632666)
    await member.add_roles(role) ```

i get an error on the last line.
sonic lintel
sick birch
#

If you don't have the right intents the only members your bot can see is itself, so even if the ID is valid it may not "see" them

#

To whoever brought that implication up, thank you, I didn't think of that

slate swan
#

It's not that.

#

Like I said before.

sick birch
#

But most of the time you can figure out the time complexity yourself. For example, utils.get is exponential time, get methods are all constant, etc

slate swan
silver wolf
slate swan
slate swan
#

There's 3.

sick birch
#

member = guild.get_member(payload.userid)
payload.userid

slate swan
#

there are only 2 reasons for get_member to return None
either you dont have member intents
or the id is wrong

slate swan
sick birch
#

It may originate from some other guild

sick birch
#

You see those a lot in interviews, e.g what's the time complexity of a merge sort?

slate swan
#

payload.user_id is a perfectly fine ID.

slate swan
# silver wolf

i was talking about explicitly mentioning that under the get_member method

sick birch
#

Right, but it's a user_id which might imply that it may be originating from off-guild

slate swan
sick birch
slate swan
sick birch
#

not list comps

sick birch
#

i don't think im ok

#

ah man it's late i need to get some rest

slate swan
#

🥺 💜

sick birch
#

my brain is starting to malfunction

slate swan
supple thorn
slate swan
#

i wonder how that happens, does the wrapper just doesnt cache the member or does the gateway not send a MEMBER_CREATE event

#

ill have to check src again on mobile😔

#

even if its not cached on the gateway connect, it gets cached on other triggers if the required intents are on, and the memory is not being limited/ cache settings are not changed iirc

pliant gulch
slate swan
pliant gulch
#

Without how the Gateway works, you get GUILD_CREATE for X guilds your bot can see, that is if you have the GUILDS intents

slate swan
#

yeah

pliant gulch
#

Since the gateway doesn't expose members inside of the GUILD_CREATE Inner payload

#

Your wrapper will send X GUILD_MEMBERS_CHUNK payloads to the gateway

#

This will then grab almost all of the members per guild, then they cache that

#

Which is what on_ready in discord.py waits for, using Futures

slate swan
#

almost 🤨

pliant gulch
#

Then from there on out, the cache is only updated by the GUILD_MEMBERS_ADD event, and the remove counter part

sonic lintel
#

My discord bot is not responding to my commands. Here is my code

pliant gulch
static lintel
#

hey guys can someone point me in the right direction to learn how to edit an embed footer using a button?

slate swan
sonic lintel
#
import disnake
import os
from disnake.ext import commands,tasks
from disnake.ext.commands import has_permissions, CheckFailure

intents = disnake.Intents.all()
client = commands.Bot(command_prefix="m/", intents=intents)


@client.event
async def on_ready():
    print("Fun is online!")

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please type in the full command.')

@client.command()
async def check(ctx, member: disnake.Member = None): 
            em = disnake.Embed(colour=disnake.Colour.blue(),
                            title="**Middleman**")
            em.set_thumbnail(url=member.avatar_url)
            em.add_field(name="User Info:",
                        value="Id: User: ",
                        inline=False)
            em.add_field(name="Vouches",
                        value="`150+`",
                        inline=False)
            em.add_field(name="Servers:",
                        value="5",
                        inline=False)
            em.add_field(name="Started Middlemanning:",
                        value="`15th of June 2021`",
                        inline=False)
            em.add_field(name="Middleman Status:",
                        value="`Dm for middleman with a fee, no fee = block. Accepting non fee requests only in server requests.`",
                        inline=False)
            em.add_field(name="Fee status:",
                        value="Middleman takes fees ands tips.",
                        inline=False)
            em.set_footer(text=f"Requested by {ctx.author}")
            await ctx.send(embed=em)```
sonic lintel
#

My bot is not responding to any of my commands

pliant gulch
#

So, "almost" is just a worst case

#

The only time you'd have an uncached member is when your bot isn't fully ready

slate swan
slate swan
sonic lintel
sonic lintel
slate swan
#

and its member.avatar.url, not member.avatar_url

pliant gulch
slate swan
#

your error handler is clearly avoiding your errors from raising

static lintel
sonic lintel
#

Ok

#

Ill let you know what happens

slate swan
#

sure

slate swan
sonic lintel
#

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 169, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/alanabeaton/Database Bot/main1.py", line 24, in check
em.set_thumbnail(url=member.avatar.url)
AttributeError: 'NoneType' object has no attribute 'avatar'

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

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "/Users/alanabeaton/Database Bot/main1.py", line 18, in on_command_error
else: raise error
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/disnake/ext/commands/core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar'

#

@slate swan

static lintel
slate swan
sonic lintel
slate swan
slate swan
sonic lintel
#

@slate swan Can you show me what it would be like in my code?

slate swan
#

the source code says otherwise

slate swan
slate swan
slate swan
#

and the rest stuff you have below remains same

#

the or operator uses the second value if the 1st one is 0, None, [], "" or any Empty iterable

sonic lintel
#

Now I am getting indent errors

#

😭

slate swan
#

well then indent it according to your code...

#

you just need to add/remove few spaces :)

sonic lintel
#

Thanks!

minor forge
#

Help me

boreal ravine
minor forge
#

how to use "while"

paper sluice
#

while is a conditional loop, that means it will keep on performing the task until the condition is satified

i = 0
while i < 10: # the condition
    print(i)
    i += 1

minor forge
#

I must program a coffee machine

#

in which I must include the "would you like another coffee?"

#

but it won't let me use "if" or "elif" after "while"

paper sluice
minor forge
#

I'm sorry