#discord-bots

1 messages · Page 565 of 1

boreal ravine
#

idk that

reef shell
#

Do you use the default help command?

coarse compass
slate swan
#

@boreal ravine spayle mssql is microsoft SQL

reef shell
#

Your bot shouldn’t behave this way tho if you are using the default help command pithink

#

Did you subclass it?

coarse compass
#

I guess it's like, It first looks for that command in it's commands, doesn't find it so sends "Not found" then suddenly finds it in one of the cogs then sends the documentation

coarse compass
reef shell
coarse compass
reef shell
#

Can u send a ss

coarse compass
#

@reef shell

reef shell
#

Not this, the ss after you invoke the cmd

#

In discord

coarse compass
#

@reef shell

reef shell
#

!d discord.ext.commands.HelpCommand.command_not_found

unkempt canyonBOT
#

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

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to `No command called {0} found.`
coarse compass
#

then why does it find it later and send it XD

reef shell
#

idk why It's happening

coarse compass
#

gotta overwrite the help I guess

#

I was thinking of doing that later but nvm

reef shell
#

Can you check if your bot is running on two instances?

coarse compass
#

@reef shell jeeeeesus you're a lifesaver and I'm stupid. I have my bot hosted on both replit and local server and I am sure I turned off the replit but somehow it turned back on 😛
The replit version is not updated so it was giving error.
It's working now, thanks

reef shell
#

xd

jade tartan
#

plz someone

surreal pebble
#

So I have an application on my PC and I want to send the same message that I send on my application onto a discord text channel.

#

Is there like an event I can use or something

unkempt canyonBOT
#

await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
surreal pebble
#

@dapper cobaltBut this needs to be under an discord.py event, right?

dapper cobalt
#

What event?

#

You can just create a command.

surreal pebble
#

But I don't want it to work on command

#

I want to run constantly

dapper cobalt
surreal pebble
#

Nono, I'm trying to make it so that when I write something on a seperate desktop application it takes that info and automatically sends it in a discord text channel.

dapper cobalt
#

Ah.

surreal pebble
#

Ye

dapper cobalt
#

Well, you can get the channel then send the message to it.

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
surreal pebble
#

But can I use discord.TextChannel.send outside of a discord event or command?

dapper cobalt
#

Get the channel and if it's a text channel it will return a discord.TextChannel object.

surreal pebble
#

@dapper cobalt Like can you do this:

async def test():
    channel = bot.get_channel(903101348000727074)
    await channel.send("hello")
#

and it's not a command or an event

dapper cobalt
#

As long as bot is your bot's instance, yes.

wintry kernel
#

muterole = discord.Role("Muted")

is this how a role is defined?

dapper cobalt
#

No.

#

!d discord.Guild.get_role click the blue title please.

unkempt canyonBOT
surreal pebble
#
import discord
from discord.ext import commands

prefix = ">"
bot = commands.Bot(command_prefix = prefix)

cogs = []

@bot.event
async def on_ready():
    print(f'BOT PRINT: Ready')

async def test():
    channel = bot.get_channel(903101348000727074)
    await channel.send("hello")

bot.run("token")
#

So like this would work?

#

Because it's not working for me

dapper cobalt
surreal pebble
#

Ohhhhh

#

I'm dumb alright thanks

#

Sick, thanks

boreal ravine
unkempt canyonBOT
#

@boreal ravine :warning: Your eval job has completed with return code 0.

[No output]
spiral frigate
#

code

import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import SlashCommand
class Info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    slash = SlashCommand(bot, sync_commands= True)

#-----------тян-----------#

    @slash.slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.")
    @commands.command(name= "тян")
    async def than(self, ctx):

        ping = round(self.bot.latency * 1000)

        embed = discord.Embed(
            title = 'Кто я?',
            description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
            colour = 0x694c5f
        )    
        embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
        embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
        embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')

        

        embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')

        await ctx.reply(embed = embed)
#

error

 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 7, in <module>
    class Info(commands.Cog):
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 11, in Info
    slash = SlashCommand(bot, sync_commands= True)
NameError: name 'bot' is not defined

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
    bot.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: NameError: name 'bot' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001AA2E05D6C0>


slate swan
#

self.bot

#

SlashCommand(self.bot)

spiral frigate
#

It still doesn't work

dapper cobalt
spiral frigate
#

that is , commands cannot do this in cog

#

then too big file will come out.

slate swan
#

the library must have some different slash command implementation in cogs for sure

boreal ravine
#

isnt it

#

cog_ext.slash

spiral frigate
#

this is where to write

slate swan
#

i dont know what library is that so no idea

boreal ravine
#

hm

slate swan
slate swan
boreal ravine
#

thats what i said

#

but i forgot about it

spiral frigate
#
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 13, in Info
    @cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.")
NameError: name 'cog_ext' is not defined

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
    bot.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: NameError: name 'cog_ext' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000001CA3F7CD6C0>
slate swan
#

import it?

#

from discord_slash import cog_ext

reef shell
#

!d discord.Status.offline

unkempt canyonBOT
reef shell
#

!d discord.ext.commands.Bot.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter.
reef shell
#

you need these two

noble fable
#

Can someone advise me functional library for discord api?

spiral frigate
rain ridge
#

Why is it not working?

@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
noble fable
slate swan
reef shell
#

1 hour

#

For global commands

noble fable
spiral frigate
reef shell
noble fable
spiral frigate
#

да

spiral frigate
boreal ravine
#

!rule 3

unkempt canyonBOT
#

3. Respect staff members and listen to their instructions.

boreal ravine
#

e wrong rule

slate swan
#

*4

boreal ravine
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

noble fable
#

It’s not perfect rule, he’s native language is Russian, so he’ll better understand in Russian

slate swan
rain ridge
#

May some1 pls tell what i am doing wrong?

@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
noble fable
#

But, sorry

slate swan
#

english is my 2nd language as well

spiral frigate
#

sorry

slate swan
boreal ravine
noble fable
#

Any errors?

rain ridge
#

no errors in code

#

but it gives error when command is used

noble fable
slate swan
#

whats that?

boreal ravine
slate swan
#

no member named .... found?

boreal ravine
#

lol

#

remove *, Ig

spiral frigate
rain ridge
#

aight i'll send

boreal ravine
#

hm

slate swan
#

or maybe NoneType has no attribute avatar_url :3

noble fable
rain ridge
#

wait

boreal ravine
rain ridge
#

The error while running cmd in discord

Traceback (most recent call last):
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/media/ranveer/New Volume/VS Code/Practice/Bot/main.py", line 98, in avatar
    userAvatarUrl = avamember.avatar_url
AttributeError: 'NoneType' object has no attribute 'avatar_url'

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

Traceback (most recent call last):
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/ranveer/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'avatar_url'```
boreal ravine
#

oh

boreal ravine
#

nonetype

slate swan
#

so , you did <prefix>avatar

#

and you except it to send your avatar right?

#

the person does not exist...

#

its a None value

noble fable
#

Ugh, mistaken

boreal ravine
#

@rain ridge u sure u did !avatar @Member

#

why delete error

#

🙃

boreal ravine
#

ooh

#

my screen

noble fable
#
@bot.command()
async def avatar(ctx,  avamember : discord.Member=None):
    if not avamember: avamember = ctx.author
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
rain ridge
#

now it worked lemon_grumpy

noble fable
#

This will be better

rain ridge
#

why it always happen

slate swan
#

it works when you mention someone

noble fable
rain ridge
#

so i have to set the value if no one is pinged then it takes user's avatar

slate swan
#
avamember = avamember or ctx.author```
rain ridge
#

thx guys it working now lemon_happy

spiral frigate
#

and the bot should be running?
To add slash commands to the server

maiden fable
#

How will you send the Slash Commands to the API lol

spiral frigate
#

yes or no

#

it takes 2 hours

steady flume
#

how to make it so that when you mention a bot, it will send a message, for example, its prefix?

maiden fable
maiden fable
unkempt canyonBOT
steady flume
#

ty

maiden fable
boreal ravine
#

hm

steady flume
#

heh

steady flume
maiden fable
boreal ravine
#

just define

maiden fable
#

Or bot.user

boreal ravine
#

or define member as the bot

#

and use that

#

¯\_(ツ)_/¯

maiden fable
#

isn't that what I told him

steady flume
#

ok

#

ok, im sorry

maiden fable
#

It's fine

maiden fable
spiral frigate
maiden fable
#

Can I see some code?

spiral frigate
#
    @cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
    async def than(self, ctx):

        ping = round(self.bot.latency * 1000)

        embed = discord.Embed(
            title = 'Кто я?',
            description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
            colour = 0x694c5f
        )    
        embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
        embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
        embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')

        

        embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')

        await ctx.reply(embed = embed)
maiden fable
#

Weird

stark bobcat
#

hello

maiden fable
#

Is there any error?

spiral frigate
#

no

maiden fable
#

Weirdddd

#

Which module u using?

#

For slash commands

spiral frigate
#

Like what I'm importing

maiden fable
#

Mhm

#

From which module

spiral frigate
#

full code

import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
class Info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

#-----------тян-----------#

    @cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
    async def than(self, ctx):

        ping = round(self.bot.latency * 1000)

        embed = discord.Embed(
            title = 'Кто я?',
            description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
            colour = 0x694c5f
        )    
        embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
        embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
        embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')

        

        embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')

        await ctx.reply(embed = embed)

def setup(bot):
    bot.add_cog(Info(bot))
    print("Ког Инфо роботает")
maiden fable
#

discord_slash

spiral frigate
#

import?

#

does not work

rigid narwhal
#

how to detect mentioned role within a command?

spiral frigate
steady flume
#

@spiral frigate что у тебя случилось ?

maiden fable
#

Welp nvm

#

U gotta see role_mentions

#

!d discord.Message.role_mentions

unkempt canyonBOT
spiral frigate
#

на русском

steady flume
maiden fable
#

Not allowed to talk in another language

steady flume
#

ya ya, we already

#

i suggested it ti him

#

to*

maiden fable
#

Ah cool

rigid narwhal
#

i tried
async def role(ctx,role : discord.Role =''):
didn't work

maiden fable
#

Use on_message

rigid narwhal
#

i want it to be a command

slate swan
#

so what doesn't work

rigid narwhal
#

were i create a category with certain roles permissions, so i want the bot to detect roles mentioned

spiral frigate
slate swan
steady flume
#

guys, dis guy wants make slash command

slate swan
#

where's the part that doesn't work

#

self is an str

#

u don't use it out of cogs either

#

I saw that

#

so why self

#

what do you want to do with it

steady flume
#

why self ?

slate swan
#

what's get

steady flume
#

its not cog

slate swan
#

ok

steady flume
#

remove self, and type client.get....

rigid narwhal
# slate swan where's the part that doesn't work

i just need the bot to detect a mentioned role in a certain command like here
async def createCategory(ctx,Role='',*, text=''):
this doesn't work when typing this
admin_role = discord.utils.get(ctx.guild.roles, name=Role)

getting this error:
Command raised an exception: InvalidArgument: target parameter must be either Member or Role

slate swan
#

don't exist

slate swan
#

pass in a string in name kwarg

rigid narwhal
slate swan
#

!d discord.utils.get

unkempt canyonBOT
#

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

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

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

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

Examples

Basic usage...
slate swan
#

I'm really dumb

#

don't switch the parameters

#

what did you type in discord, what roles are there?

rigid narwhal
#

"admin" role i need to create a new category with access for this role

slate swan
#

that's what I just said

#

don't exist

#

on what do you want to use get

slate swan
#

then mention the role in the command

#

then u wouldn't have to use get()

rigid narwhal
slate swan
#

with what error Androx

#

I'm currently talking to three people, chill

rigid narwhal
#

let me redo it and send the error sorry xd

slate swan
#

paid for asking for help

#

what do you want to use get() on?

#

stop the shitposts

spiral frigate
#

Code:

import random
import discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
class Info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

#-----------тян-----------#

    @cog_ext.cog_slash(name= "тян", description= "С помощью этой команды ты узнаешь кто я такая.", guild_ids= [894452684072046652])
    async def than(self, ctx):

        ping = round(self.bot.latency * 1000)

        embed = discord.Embed(
            title = 'Кто я?',
            description = 'Я не большой бот, зовут меня **Сузуки**, надеюсь запомните.\nКак и все боты в моём стиле я `Тянка`. Ладно что-то я отвлеклась.\n\nЧто я могу? Ну в принципе как все боты я имею команды, для:\n`Модерации`, `Веселья`, `Получения информации`.\n\nНу на этом пока всё. Мой `Семпай` трудится и делает меня \n`Лучше`, `Красивее` и `Продвинутой`.',
            colour = 0x694c5f
        )    
        embed.add_field(name= 'Имя:', value= '>>> `Сузуки`')
        embed.add_field(name= 'Создатель:', value= '>>> `Барабан4ик#3148`')
        embed.add_field(name= 'Пинг:', value= f'>>> `{ping} мс`')

        

        embed.set_footer(text= 'Барабан4ик © 2021 Все права у тянок', icon_url= 'https://cdn.discordapp.com/avatars/637685929611493422/32b105aa2097b6a3a84b2cda2f7b8e00.png?size=128')

        await ctx.reply(embed = embed)

def setup(bot):
    bot.add_cog(Info(bot))
    print("Ког Инфо роботает")

problem:
There are no slash commands at all there is no error
Library:
Discord.py

slate swan
#

paid for copying code and then not understanding it

#

I'm gonna guess the person gave you the code used cogs

#

and he had a get function in the cog

spiral frigate
#

I have already added 'applications.commands`

slate swan
#

a really complex one

steady flume
#

how to make it so that when you mention a bot, it will send a message, for example, its prefix?

steady flume
#
bot = ['@rotund oxide']

@commands.Cog.listener()
    async def on_message(self, message):
        author = message.author
        msg = message.content.lower()
if msg in bot:
            await message.channel.send(embed=discord.Embed(description=f"My prefix is {message.channel.prefix}"))

didnt help

#

on_message

slate swan
#

!d discord.ext.commands.Bot.user

unkempt canyonBOT
slate swan
#

!d discord.Member.mentioned_in

unkempt canyonBOT
steady flume
#

doesnt work

slate swan
#

did you use what I just sent?

steady flume
slate swan
#

well what do you expect then

steady flume
#

tbh didnt understand how to use it

slate swan
#

if bot.user.mentioned_in(message)

#

then you can do what you want

steady flume
#

msg = message.content.lower()

slate swan
#

no

#

message wouldn't be a string

#

it would be the whole message

steady flume
#

where i need put it ?

slate swan
#

not like you write your own code for money

steady flume
#

im a bit dumb, ik

slate swan
#

just at the front

steady flume
#

ohk, ty

slate swan
#

told u

#

the person u copied had a get function in the cog

#

you also have to move to cogs

slate swan
#

or set the function somewhere and be able to know how to use it

#

basic python

#

you're gonna make me really mad if you continue

#
  1. define the function
  2. use it
spiral frigate
#

and what do I have to rewrite the whole code now

#

or is everything the same there

slate swan
#

everything that is in dpy is usable

steady flume
#

ty guys!

slate swan
#

if you need something else, import it

steady flume
#

now all works!

slate swan
#

nice

shy bane
#

Hello guys i need help with discord.py slash commands

#

do someone know why it's not working?

slim whale
#
@bot.command()
async def badges(ctx, user: discord.Member = None):
  await ctx.send(discord.PublicUserFlags_all())```how i can make it print ur badges?
shy bane
#

i'am trying 1 hour to try to fix it

#

what?

slate swan
#

what the heck

shy bane
#

really?

slate swan
#

this is just pure shitposting

slate swan
shy bane
#

oh it's very sad

shy bane
#

what no

slate swan
#

it's not

slim whale
#

f

shy bane
#

ok

slate swan
#

!d discord.Member.public_flags

unkempt canyonBOT
#

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

u dum

#

it's from discord.ext

#

from discord.ext import commands

slim whale
slate swan
#

sure

#

probably some weird outcome

slate swan
#

but surely customizable

#

yes

slim whale
#

oh

slate swan
#

a list would come out

shy bane
slate swan
#

with names in it

slim whale
#

okey, i will try and then i implement it to a userinfo

spiral frigate
#

can you write what to replace here

import random
import nextcord as discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
slate swan
shy bane
#

OK

slim whale
#

U DO BRO

shy bane
#

why

novel apexBOT
#

This is not a Modmail thread.

shy bane
#

i have pycramp

slim whale
#

go to packages, and then install discord

shy bane
#

but i don't really use it

slim whale
#

the first package

slate swan
spiral frigate
#

can you write what to replace here

import random
import nextcord as discord
from discord.ext import commands
import datetime as DT
from discord.ext.commands.errors import MemberNotFound
from discord_slash import cog_ext
import discord_slash
slate swan
#

R. Danny isn't here bro

#

I'm done

spiral frigate
#

ok

slim whale
#

wtf is nextcord

#

just go to packages and then install discord

#

from discord.ext import commands and do this (?)

slate swan
#

just let him be

slim whale
#

okay

#

why?

slate swan
#

he copies code for money, doesn't understand it and then tries to force people to use some fork or smth

slim whale
#

<PublicUserFlags value=128> what does this mean XD? @slate swan

hasty iron
#

its a repr

#

!d object.repr

slate swan
unkempt canyonBOT
#

object.__repr__(self)```
Called by the [`repr()`](https://docs.python.org/3/library/functions.html#repr "repr") built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form `<...some useful description...>` should be returned. The return value must be a string object. If a class defines [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") but not [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__ "object.__str__"), then [`__repr__()`](https://docs.python.org/3/reference/datamodel.html#object.__repr__ "object.__repr__") is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
slim whale
hasty iron
#

you can’t, it’s a representation of the object

#

you need to use whatever attributes of that flag to make the emote badges or whatever

#

for example a mapping of flag name to emote

slate swan
#

the bot doesn't accept brackets

hasty iron
#

hm, anyways, UserPublicFlags is an iterable

slim whale
#
await ctx.send(__repr__(user.public_flags))
#

this?¿

hasty iron
#

what

slate swan
#

meh then no

spiral frigate
#
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 661, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 6, in <module>
    from discord_slash import cog_ext
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\__init__.py", line 9, in <module>
    from .client import SlashCommand  # noqa: F401
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_slash\client.py", line 9, in <module>
    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)


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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\Desktop\Suzuki\bot.py", line 51, in <module>
    bot.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 733, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 664, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.info' raised an error: ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000015251C43AC0>
hasty iron
#

learn python please

slim whale
#

i dont understand what u were saying bruh

hasty iron
#

it’s stuff you should already know

slate swan
#

Imma look at the source of this bot

#

how it does this

hasty iron
#

considering you’re using dpy

slate swan
#

public_flags has some attributes that are usable

slate swan
#

they all return true if the user has those badges

#
        for badge, is_set in user.public_flags:
            if is_set and (emoji := getattr(constants.Emojis, f"badge_{badge}", None)):
                badges.append(emoji)
#

yep, they have all of the emojis, which they add if the user has the right badge

spiral frigate
shy bane
#

Someone can to help me?

slate swan
#

Install discord-py-interactions with pip

shy bane
#

Oopes

#

this is what it's say

#

it's say it's unknow command

shy bane
#

oh wait

slate swan
#

install

shy bane
#

i need with the install

#

yeah

shy bane
#

i did it

slate swan
#

Did what?

shy bane
#

did the pip install discord-py-interactions

#

and it's still doing error

slate swan
#

And what does it show? Sorry but I can't see your screen from where I am...

shy bane
#

this is what it's say
@slate swan

slate swan
#

Error is explained

shy bane
#

i did every youtube toturile

slate swan
#

1: Uninstall discord.py
2: Use commands.Bot instead of discord.Client

shy bane
#

like all of the discord slash command

slate swan
#

Just read the error, everything is explained

shy bane
#

2: Use commands.Bot instead of discord.Client
?

slate swan
#

You have nextcord and discord.py installed. Only use one

shy bane
#

what

slate swan
#

Stop using discord.Client(), use commands.Bot()

spiral frigate
#

nextcord has support for slash commands

shy bane
#

where is the discord.Client

#

oh i see

slate swan
#

yes?

#

why doesnt my ban command work its just not working anymore after like a few months

  try:
                        await user.ban(user,reason=None, delete_message_days=7)
                        print (f"{user.name} Was Banned")

                    except:
                        pass
spiral frigate
#

and where is there

#

so yes or no

#

and where is there

slim whale
#

send whole code

slate swan
shy bane
slim whale
#

i think that its right

shy bane
#

what worng with line 4

spiral frigate
#

where there is

shy bane
#

what

slate swan
leaden jasper
shy bane
#

i did

#

i will do again

#

i did

#

yes i use

#

OK

#

GUYS

#

and now it's doing only one eroor

slate swan
#

Maybe give a token?

slate swan
# slim whale send code please
for member in ctx.guild.members:
            for user in list(ctx.guild.members):
                if not user.bot:
                    try:
                        await user.ban(user,reason=None, delete_message_days=7)
                        print (f"{user.name} Was Banned")

yes i know its a bit sketchy but its for my penetration bot thats in my github

shy bane
#

omg it's doing again

magic pond
#

how do i make my bot log my server votes

shy bane
#

i did

slim whale
mint jolt
shy bane
slim whale
#

it is in his github, the command its well done

shy bane
#

what the

slim whale
#

i think (?)

slate swan
#

wait i think i have to put member: discord.member

#

let me try

shy bane
#

k

slate swan
slim whale
mint jolt
slim whale
#

i dont know cogs

shy bane
#

ok what the i did

slim whale
mint jolt
#

I'm writing code with vs code

slim whale
#

yes but he is using replt

mint jolt
#

and pychram

icy mango
#

is there any thing in dpy like on_message_delete or on_message_edit

shy bane
#

pyCharm is ok ? @slate swan

#

in vs code it's just don't wanna to install discord.py

#

for me

mint jolt
shy bane
#

ok guys i think i need to move to discord.js

#

gtg byeeeeeeeeeeeeeeeeeeeeeeee

#

i will try and if it's not good i will come back

slim whale
#

X

brazen raft
#

You can move to forks of discord.py or to other libraries such as hikari

slim whale
#

D

#

but why u start with slash commands directly @shy bane first try something like ctx.send("hello world ")

#

idk

prisma folio
#

Hello, everyone! Is there a way for me to make my Discord bot detect the HypeSquad house that the user is in and the user's name?

#

And/or.*.

shy bane
#

i know how to do it but the slash command is not working for me

slim whale
prisma folio
#

Okay. Thank you! :).

slim whale
slim whale
prisma folio
#

Ah! Thanks a lot and that sounds cool!

shy bane
#

or not

slate swan
spiral frigate
#
    @commands.command(name= "профиль")
    async def profile(self, ctx: commands.Context,member:discord.Member = None, guild: discord.Guild = None):
        if member == None:

            embed = discord.Embed (
            title = 'Ваш профиль',
            colour = ctx.message.author.color
        )
            t = ctx.message.author.status
            if t == discord.Status.online:
                d = "🟢 В сети"

            t = ctx.message.author.status
            if t == discord.Status.offline:
                d = "◉ Не в сети"

            t = ctx.message.author.status
            if t == discord.Status.idle:
                d = "🌙 Не активен"

            t = ctx.message.author.status
            if t == discord.Status.dnd:
                d = "⛔ Не беспокоить"

            embed.add_field(name= "Ник:", value = ctx.message.author.mention)
            embed.add_field(name= "Статус:", value=f"`{d}`")
            embed.add_field(name= "Основная роль:", value = ctx.message.author.top_role.mention)
            embed.add_field(name= "Дата создания:", value = f"<t:{int(ctx.message.author.created_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
            embed.add_field(name= "Дата присоединения:", value= f"<t:{int(ctx.message.author.joined_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
            embed.add_field(name= "Количество ролей:", value=f"`{len(ctx.message.author.roles)- 1}`")
            embed.set_thumbnail(url=ctx.message.author.avatar_url)

            await ctx.reply(embed = embed)
unkempt canyonBOT
#

property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
spiral frigate
#
        else:

            embed = discord.Embed (
            title = f'Профиль **{member.display_name}**',
            colour = member.color
        )
            t = member.status
            if t == discord.Status.online:
                d = "🟢 В сети"

            t = member.status
            if t == discord.Status.offline:
                d = "◉ Не в сети"

            t = member.status
            if t == discord.Status.idle:
                d = "🌙 Не активен"

            t = member.status
            if t == discord.Status.dnd:
                d = "⛔ Не беспокоить"

            embed.add_field(name= "Ник:", value = member.mention)
            embed.add_field(name= "Статус:", value=f"`{d}`")
            embed.add_field(name= "Основная роль:", value = member.top_role.mention)
            embed.add_field(name= "Дата создания:", value = f"<t:{int(member.created_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
            embed.add_field(name= "Дата присоединения:", value= f"<t:{int(member.joined_at.replace(tzinfo=DT.timezone.utc).timestamp())}:D>")
            embed.add_field(name= "Количество ролей:", value=f"`{len(member.roles)- 1}`")
            embed.set_thumbnail(url=member.avatar_url)

            await ctx.reply(embed = embed)
mint jolt
spiral frigate
#
    @profile.error
    async def profile_error(self, ctx, error):
       if isinstance(error, MemberNotFound):

           embed = discord.Embed (
           title = 'Команда `s~профиль`',
           description = 'Команда `s~профиль` выведет основную \n информацию о тебе или о другой милашке. ',
           colour = 0x694c5f
        )
           embed.add_field(name= "Информацию которою я знаю:", value = ">>> `Ник`, `Статус`, `Основная роль`, `Дата создания`...", inline= False)
           embed.add_field(name= "Использование:", value = ">>> `~s профиль` `<Участник>`", inline= False)
           embed.add_field(name= "Параметры:", value = ">>> `<>` - Необязательный параметр \n `()` - Обязательный параметр", inline= False)
           embed.add_field(name= "Пример 1:", value = ">>> `s~профиль` \n ⮩ Выведет информацию о вас", inline= False)
           embed.add_field(name= "Пример 2:", value = ">>> `s~профиль` `<Участник>` \n ⮩ Выведет информацию о участнике", inline= False)

           await ctx.reply(embed = embed)
slim whale
spiral frigate
slate swan
#

*User

prisma folio
slim whale
#

oh yes

mint jolt
slate swan
spiral frigate
slim whale
slate swan
spiral frigate
#

it's just that the bot is not responding

slim whale
prisma folio
slate swan
spiral frigate
#

other work

slate swan
slim whale
spiral frigate
#
  File "C:\Users\Baraban4ik\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\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 143, in profile
    embed.set_thumbnail(url=ctx.message.author.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 995, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 895, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Baraban4ik\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: 'Member' object has no attribute 'avatar_url'

slate swan
broken igloo
#

Hello! How to create scheduler which doesn’t reset tasks on bot restart?

slim whale
#
@bot.command()
async def badges(ctx, user: discord.Member = None):
  await ctx.send(repr(user.public_flags.all()))```how i can make this to print more than one badge?
slate swan
#

WHY do i get error no module named discord

#

omggggggggggg

slate swan
slate swan
#

i think yes

cyan bay
#

btw how do u use the reddit api

slate swan
#

i got 3.10 3.9 and 3.7 i think

slim whale
slate swan
#

how do i uninstall some

cyan bay
slate swan
#

oo ok

mint jolt
#

I had written this in my project, just how to make it@slim whale

slim whale
slim whale
#

idk what are u saying xd

slate swan
cyan bay
#

does anyone know how to use the reddit api?

mint jolt
slate swan
slim whale
slim whale
cyan bay
# slate swan the praw library?

idk, the goal im looking for is fr my bot to be able to post random memes after the user says a certain command, like dank memer

surreal pebble
#
Traceback (most recent call last):
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
    self.on_press(key)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "pepepopo.py", line 20, in on_press
    asyncio.run(send_message())
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "pepepopo.py", line 18, in send_message
    await channel.send(str(key))
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 856, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 165, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 426, in _request
    with timer:
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 579, in __enter__
    raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
#
def on_press(key):
    print(key)

    async def send_message():
        print("peepeepoopoo")
        channel = bot.get_channel(903101348000727074)
        await channel.send(str(key))

    asyncio.run(send_message())

pepe = 1
if 1 == pepe:
    listener = keyboard.Listener(on_press = on_press)
    listener.start()```
slate swan
slate swan
#

oh nvm

slate swan
#

it gave

slate swan
slate swan
icy mango
cyan bay
#

sorry to bother but, the async praw thingy is kinda confusing, can you gimme a brief rundown?

icy mango
slate swan
icy mango
#

i found

slate swan
unkempt canyonBOT
#

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

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

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

how do I convert a tuple to a string? I tried doing it like this:

@bot.command()
def claim(*role_arg):
  # prepare (role:req)
  claimable = ['based lord:5', 'big:10', 'u:20']
  role_f = ''.join(list(role_arg))
  role_f = role_f.lower()

however, if I try to do claim based lord it returns basedlord instead of based lord

spiral frigate
slate swan
brazen raft
cyan bay
surreal pebble
#

N E E D A S S I S T A N C E F I R S T

slate swan
#

@slim whale

await ctx.guild.ban(user)

thats part of my code that doesnt work anymore i tried mentioning all the users in the guild and it worked so thats how i know it doesnt work

surreal pebble
#

Get user object

#

also you ban a member

#

Not a user, I think

slate swan
surreal pebble
#

Well what is this in?

#

Like is it in a command

#

maybe ctx isn't giving you the guild?

#

Maybe you have to get the guild object too

slate swan
# cyan bay **n e e d a s s i s t a n c e t o o**

In this video, we will learn how to get data from Reddit using python for a Discord bot. We will make the meme command in this video.

If you have any suggestions for future videos, leave it in the comments below.

Some Useful Links -

Reddit Applications- https://reddit.com/prefs/apps
My Discord Server- https://discord.gg/TXF3hBj

My Twitter...

▶ Play video
cyan bay
slate swan
cyan bay
#

absolute legend

slate swan
cyan bay
#

tysm

surreal pebble
#

S A V E M E P L S

slate swan
surreal pebble
#

y o u f i r s t

slate swan
surreal pebble
#

Lol nope

slate swan
#

same

slate swan
surreal pebble
#

Okay, I understand nothing.

#

Asyncio.create_task where

#

And where am I running and event loop?

blazing beacon
#
@bot.event
async def on_raw_reaction_add(payload):
    if payload.channel_id == 866024988901638185 and payload.emoji.name == ":cantrash:":
      channel = bot.get_channel(614467771866021944)                                  ^^^ - EOL while scanning literal

      message = await channel.fetch_message(payload.message_id)

      reaction = get(message.reactions, emoji=payload.emoji.name)

      if reaction and reaction.count > 1:
        
        await message.delete()
slate swan
surreal pebble
#

Ohhhhh, so just replace asyncio.run with asyncio.create_task

slate swan
#

sure, you need to read more on event loop if you have no idea what i meant

surreal pebble
#

Alright, and that is in the asyncio docs?

#
def on_press(key):
    print(key)
    async def send_message():
        print("peepeepoopoo")
        channel = bot.get_channel(903101348000727074)
        await channel.send(str(key))

    asyncio.create_task(send_message())

pepe = 1
if 1 == pepe:
    listener = keyboard.Listener(on_press = on_press)
    listener.start()
#
Unhandled exception in listener callback
Traceback (most recent call last):
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 162, in inner
    return f(self, *args, **kwargs)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
    self.on_press(key)
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\site-packages\pynput\_util\__init__.py", line 78, in inner
    if f(*args) is False:
  File "pepepopo.py", line 20, in on_press
    asyncio.create_task(send_message())
  File "C:\Users\imkru\AppData\Local\Programs\Python\Python38\lib\asyncio\tasks.py", line 381, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop
slate swan
#

I see, are you not even running the bot

surreal pebble
#

It should be running

#

sec I can show all code

slate swan
#

just use the bot's loop then, bot.loop.create_task

surreal pebble
#
prefix = ">"
bot = commands.Bot(command_prefix = prefix)

def on_press(key):
    print(key)

    async def send_message():
        print("peepeepoopoo")
        channel = bot.get_channel(903101348000727074)
        await channel.send(str(key))

    asyncio.create_task(send_message())

pepe = 1
if 1 == pepe:
    listener = keyboard.Listener(on_press = on_press)
    listener.start()

@bot.event
async def on_ready():
    print(f'BOT PRINT: Ready')

    # Calling functions:

bot.run("token")
surreal pebble
#

fuck yeah, got it

#

Thanks 😄

#

Finally

slate swan
#

about the event loop part, asyncio docs doesn't talk about it in a walkthrough so

#

gotta learn it somewhere idk i forgot where i read it

surreal pebble
#

Oh alright, do I just google "event loops python"?

slate swan
slim whale
#

it would be user.ban()

slate swan
slim whale
#

okay

#
@bot.command()
async def badges(ctx, user: discord.Member = None):
  await ctx.send(str(user.public_flags.all()))```can someone help me? the bots only prints one badge and it prints this [<UserFlags.hypesquad_brilliance: 128>]
slate swan
#

how many badges does the user have

slim whale
slate swan
#

even tho he has more

slim whale
#

yes

slate swan
slim whale
slate swan
#

how can I add this error

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.3.value: Must be 1024 or fewer in length.

to my error handler?

    @_profile.error
    async def profile_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send(error)```
slim whale
#

but boost badge? im going to try it

slate swan
slim whale
#

@bot.command()
async def ban(ctx, user: discord.User): leaving this at the top i think

#

badges no

slate swan
slim whale
#

@slate swan it works [<UserFlags.partner: 2>, <UserFlags.hypesquad_bravery: 64>], but how i can make it print another thing?

slim whale
#

without the userflags.parter: 2 etc

slate swan
#
    @_profile.error
    async def profile_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
        elif isinstance(error, HTTPException):
            await ctx.send(error)```
slate swan
slim whale
#

then make it an emoji, for a userinfo

slate swan
# slim whale Yes

user.public_flags supports iter which returns (name, value) where value is a boolean
so just make a list comp that filter out value that is false, to just get the name

slim whale
#

what its a iter first of all xd?

hollow plover
#

hello how do you make the dropdown thing s and buttons without dpy 2.0 because I can't download it

slate swan
# slim whale dont understand

iter is a built-in function that returns a generator which you can iterate through, in simple term, you can for loop whatever iter returns,
for example ```py

user = bot.get_user(80088516616269824)
list(iter(user.public_flags))
[('staff', False), ('partner', False), ('hypesquad', False), ('bug_hunter', False), ('hypesquad_bravery', False), ('hypesquad_brilliance', False), ('hypesquad_balance', True), ('early_supporter', True), ('team_user', False), ('system', False), ('bug_hunter_level_2', False), ('verified_bot', False), ('verified_bot_developer', False), ('discord_certified_moderator', True)]

[x for x, v in iter(user.public_flags) if v]
['hypesquad_balance', 'early_supporter', 'discord_certified_moderator']

slim whale
#

or the x for x

slate swan
#

the list comp is the last step

#

list(iter(user.public_flags)) is just what you would see if you're only casting it to a list without filtering

slim whale
#

and then i need to do ctx.send(list) ?

placid skiff
slate swan
slim whale
#

>>> and what does this mean? spaces?

slate swan
slate swan
#

how can I add this error

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.3.value: Must be 1024 or fewer in length.

to my error handler?

    @_profile.error
    async def profile_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.message.delete()
            await ctx.send(error, delete_after=5)```
#

everything i've tried hasn't worked

slim whale
slate swan
#

no?

placid skiff
#

!d discord.ext.commands.errors.CommandInvokeError

unkempt canyonBOT
#

exception discord.ext.commands.CommandInvokeError(e)```
Exception raised when the command being invoked raised an exception.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
slate swan
# slim whale but i need to put more names to the filter no?

in that code v is your Boolean, it is True when the user has that badge, and False when the user doesn't have that badge, if v means if v is True, then append them in a list, it would look the same as ```py
badges = []
for x, v in iter(user.public_flags):
if v:
badges.append(x)

so it will only append if `v` is True
slate swan
upbeat otter
#

Guys, I am using discord_slash, but the commands arent loading, what do I do?

slate swan
#

So i've copped this piece of code from stackoverflow and i have never coded with the discord api before and it's giving me a nonetype error when i try to send the dm message. why is that?


Token = # censored

client = discord.Client()

@client.event
async def on_ready():
    yourID = "469610757512888322"
    discordUser = client.get_user(yourID)

    await discordUser.send('gibberish')

client.run(Token)
slate swan
#

thanks

upbeat otter
#

!d discord.DMChannel

unkempt canyonBOT
#

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

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns a string representation of the channel
slate swan
#

now you caught me off guard, where should i implement it?

#

And vscode is wanting me to use "fetch_by_id"

upbeat otter
slate swan
#

how can i make my bot refuse an input and tell someone to send another message if its over a certain amount of characters?

upbeat otter
upbeat otter
slate swan
#

sec will get you code

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

upbeat otter
#

sure

slate swan
upbeat otter
#

just a minute

upbeat otter
slate swan
#

43

#

i think would be the correct place

upbeat otter
hollow plover
slate swan
#

does that make it harder?

upbeat otter
slate swan
#

ah okay

placid skiff
slate swan
#

where does that go?

upbeat otter
placid skiff
#

So you have to put a while loop. Before your wait_for

upbeat otter
#

and indent the rest of the code outside the if statement

placid skiff
#

In that loop ask the user for the input

upbeat otter
placid skiff
#

Yes, he has to request the input until the amount is correct

#

So in the while loop ask for the input, check the len, if it satisfy your condition then break the loop, else continue with the loop

#

You have to break the loop even if the timeout is triggered

slate swan
#

Extension 'cogs.Commands' raised an error: SyntaxError: invalid syntax (Commands.py, line 45)

pallid meadow
#

Can you show your code?

slate swan
#

i've never worked with while loops, how would i implement it?

placid skiff
#

Bro then you have just to quit wathever you are doing and study python
Is not possible to make a discord.py bot if you don't know python

slate swan
#

this is legit the last thing i need then my bots done lol

#

i started learning python today and wrote all that

placid skiff
#

And that seems good but I had just a rapid look and i found a lot of errors and no-sense things

slate swan
#

hello. i have this directory and i want to import it but an error occurs

placid skiff
#

I guessed that you are starting learning discord.py but i hoped that you already knew python lol

slate swan
#
for filename in os.listdir('./src/commands/ticket'):
  if filename.endswith('.py'):
    j1mk0l.load_extension(f'ticket.{filename[:-3]}')
#

nope lol i learnt both same time xD

#

i need this bot for my friends and too poor to pay for a dev so have to learn myself

placid skiff
slate swan
#

i will definitely start looking at it more in depth from now, i am having a lot of fun learning

slate swan
#

and now im getting this

slim whale
#

@slate swan ```py
@bot.command()
async def badges(ctx, user: discord.User = None):
if user is None:
user = ctx.author

list(iter(user.public_flags))
[('staff', False), ('partner', False), ('hypesquad', False), ('bug_hunter', False), ('hypesquad_bravery', False), ('hypesquad_brilliance', False), ('hypesquad_balance', True), ('early_supporter', True), ('team_user', False), ('system', False), ('bug_hunter_level_2', False), ('verified_bot', False), ('verified_bot_developer', False), ('discord_certified_moderator', True)]

badges = []
for x, v in iter(user.public_flags):
if v:
badges.append(x)

await ctx.send(x)

#

oh

#

forgot await xd

slate swan
slate swan
rotund nova
#

some know what do

slate swan
#

        async def askQuestion(question):
            await ctx.author.send(question)
            print(f"Waiting for reply from {member}...")
            userReply = await self.bot.wait_for('message', check=check)
            while len(UserReply.content) > 1000:
                ctx.author.send("too many characters")
                if len(UserReply.content) < 1000:
                    break
            print(f"{member} replied")
            return userReply.content
``` @placid skiff
#

this is what my code looks like while i try using a loop

#

it sends the question but doesn't progress when i reply

rotund nova
#
@client.event
async def on_message(message, ctx, suggestion):
    if message.channel.name != "suggestions":
        return
    await message.add_reaction('✅')
    await message.add_reaction('❌')
        
        embed = discord.Embed(title="no c", description=f"cc", colour=discord.Colour.light_gray())
        embed.add_field(name="Sugestie dał {ctx.author.name}", icon_url = {ctx.author.avatar_url}, inline=False)
        embed.add_field(name="Mowa sugestia!", value=f"{suggestion}", inline=False)

        await ctx.send(embed=embed)
``` its code
placid skiff
surreal pebble
#

How do I join different strings in an array?

slate swan
#

        async def askQuestion(question):
            await ctx.author.send(question)
            print(f"Waiting for reply from {member}...")
            next_step = false
            while next_step:
                userReply = await self.bot.wait_for('message', check=check)
                if len(userReply) < 1000:
                    print(f"{member} replied")
                    return userReply.content
                else:
                    next_step = true
        lookingFor = await askQuestion(questions[0])
        lookingTags = await askQuestion(questions[1])

``` can someone tell me why this doesn't progress past Waiting for reply from r0yal#2029... ? it just never continues after you reply
hasty iron
#

what is false and true

#

also follow naming conventions

surreal pebble
#
async def send_message():
    global keys, count
    await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys))
    print(len(keys))
    keys = []

def on_press(key):
    global keys, count
    keys.append(str(key))
    count += 1
    if count >= 20:
        count = 0
        print("ppppppeeeeeennnnnn")
        bot.loop.create_task(send_message())

pepe = 1
if 1 == pepe:
    listener = keyboard.Listener(on_press = on_press)
    listener.start()

Can you have multiple bot.loop.create_task(send_message()) of these loops running at once if you don't cancel them before declaring another one? The bot is supposed to get all of the characters I type on my keyboard, store those characters in the keys array, wait until there are 20 characters in total, and then executes the send_message function, then that function clears the keys array once it sends all of the 20 characters in my text channel. Everything works except for actually sending the message because there seems to be some issue here: py async def send_message(): global keys, count await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys)) print(len(keys)) keys = [] Essentially, my question is: is there something running in the background or something I'm missing/ doing wrong here that is making the bot send the characters I type on my keyboard send to my text channel in weird and wrong ways?

hasty iron
#

if listener.start() blocks the event loop, your task wont run

surreal pebble
#

Well send_message does run

#

Just not when it's supposed to

hasty iron
#

yes because its blocks the execution

surreal pebble
#

How do I fix that?

hasty iron
#

not use a blocking library

surreal pebble
#

Well listener is supposed to be non-blocking

#
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.start()
#

^ From docs

hasty iron
#

hm, give me a second

surreal pebble
#

Alright, thanks by the way

hasty iron
#

what library is that

surreal pebble
#

keyboard

hasty iron
#

ok thanks

surreal pebble
#

I mean pynput

#

Sorry my bad, I forgot by mistake @hasty iron

hasty iron
#

oh

#

ok

surreal pebble
#

😬 sorry

hasty iron
#

its fine

hasty iron
#

and is the event loop running somewhere?

surreal pebble
#

Well the function is ran really randomly like i don’t understand it’s sequence at all

#

And what do you mean by event loop?

hasty iron
#

the asyncio event loop, for example, is the bot running

surreal pebble
#

Oh, yeah the bot is up

#

The function gets sent but not at the right times

#

Could this be because I have a slow connection?

#

And I’m hosting on my internet

#

(While it’s slow)

hasty iron
#

can you add debug prints

#

to see if it runs your task

surreal pebble
#

Yeah, I’ll send now

#
async def send_message():
    global keys, count
    await bot.get_guild(903101348000727070).get_channel(903101348000727074).send(" | ".join(keys))
    print(len(keys))
    print(keys)
    keys = []

def on_press(key):
    global keys, count
    keys.append(str(key))
    count += 1

    print(count)
    if count >= 20:
        count = 0
        print("ppppppeeeeeennnnnn")
        bot.loop.create_task(send_message())

pepe = 1
if 1 == pepe:
    listener = keyboard.Listener(on_press = on_press)
    listener.start()
#

So I added one in send_message

#

and another in on_press

#

And this is the output

#

That is the number of characters I've typed

#

and then that longer thing is the print(keys) in send_message

#

and that 31 that you see in the output is from print(len(keys)), which is supposed to 0 before printing that long output.

#

@hasty iron

hasty iron
#

does it always delay the execution?

surreal pebble
#

It's pretty random, but yeah always. Let me double check

#

Ohhhh

#

Okay so for the first execution it works correctly

#

I think

#

But then it doesn't work again for another like 40 messages

#

There is something wrong in the loops I think. @hasty iron

hasty iron
#

hm

surreal pebble
#

it's either that or my internet is the problem

#

Because I just don't understand what else could cause it

#

Is there like another completely different way I can do this, you think?

hasty iron
#

no sorry i cant think of anything

surreal pebble
#

Alright, thanks anyways

pale zenith
#

🤔

rotund nova
kindred epoch
#

almost everything in that code is wrong

slate swan
#

I'm so confused to why this isn't working can someone help figure it out?

        @commands.Cog.listener()
        async def on_member_join(member):
            print(f"{member.name} joined.")
```There is no errors
#

how do i add all intents and do i have to add something in the portal?

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.

kindred epoch
slate swan
#
import discord
import pymongo
from pymongo import MongoClient
import os
from discord.ext import commands

class BalCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

        @commands.Cog.listener()
        async def on_member_join(member):
            print(f"{member.name} joined.")


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

Could it be something to do with my cogs?

slate swan
slate swan
# kindred epoch do you have intents?

yeah this is in main.py

import discord
from discord.ext import commands
from discord import Intents


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

bot = commands.Bot(command_prefix="#", intents=intents)
kindred epoch
slate swan
slate swan
# kindred epoch are you loading the cogs?

Yes heres the entire main.py

import discord
from discord.ext import commands
from discord import Intents
import os


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

bot = commands.Bot(command_prefix="#", intents=intents)
bot.remove_command("help")

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')

@bot.event
async def on_ready():
    print(bot.user.name + " is online.")

bot.run("token")
kindred epoch
slate swan
#

ahhhhh

#

Still nothing happens

kindred epoch
#

its supposed to be 4 not 8

#

so right under def init

slate swan
#

I'm confused, which part are you talking about?

#

ohhh

kindred epoch
#

the event

slate swan
#

Yeah

kindred epoch
#

it needs to be indented only 4 spaces

slate swan
#

I understand, so like this?

kindred epoch
#
@commands.Cog.listener()
async def on_member_join(member):
    print(f"{member.name} joined.")
``` this part of code needs to be indented only 4 spaces
#

ye

dense swallow
#

missed out self

slate swan
#

How do I do {member.name} with their tag

#

instead of just their username

#

is it like this?

user.username+"#"+str(user.discriminator)
zinc reef
slate swan
#

oh really

zinc reef
#

the __str__ formats it with the discriminator already

kindred epoch
#

what have you tried so far

#

we're not gonna spoonfeed u

slate swan
#

Is there a way to do something for every user existing in a server except bots?

zinc reef
#

loop over guild.members, check if not member.bot

slate swan
#

Are you using cogs?

#

then remove self

crystal rapids
#

Even if it was cog, self should've been the first parameter not second cough

slate swan
zinc reef
wanton cipher
slate swan
#

does anybody know how to get a groupchat from its id?

#

like py gc = bot.get_groupchat(123456789) or sumthing

#

when i do bot.get_channel(gc_id) it returns ```py
None

jovial flare
#

Hello everyone, how to make the text look like it is from python?

bold oxide
#

do tildas

#

` <--- three of these

#

on each side of your text

jovial flare
#

Thanks!!

bold oxide
#

I am trying to make a bot that kicks unverified members, when i run it and type the command, nothing happens. Anyone know why? @bot.command(pass_context=True) async def kickem(ctx): guild = ctx.guild for member in tuple(guild.members): if len(member.roles) == 1: await bot.kick(member)

slate swan
#

does anybody know how to get a groupchat from its id?
like
gc = bot.get_groupchat(123456789)
or sumthing
when i do bot.get_channel(gc_id) it returns
None

brave phoenix
#

Wouldn’t that be impossible as you need to be a friend with a user to add ‘‘em to a group but you can’t friend a bot

brave phoenix
bold oxide
#

still nothing

slate swan
#

When I hover my cursor over else it says "Expected Expression" and is underlined red therefore meaning there is something wrong with it. How do I fix this?

        if user is None:

            results = collection.find({"_id":f"{ctx.author.id}"})

        for result in results:
            bal_em = discord.Embed(title = f"{ctx.author.name}'s Balance", description = f"{ctx.author} has a balance of " + result["balance"],colour=0xFFA500)
        await ctx.send(embed=bal_em)

        else:

        results = collection.find({"_id":f"{user.id}"})

        for result in results:
            bal_em = discord.Embed(title = f"{user.name}'s Balance", description = f"{user} has a balance of " + result["balance"],colour=0xFFA500)
        await ctx.send(embed=bal_em)
#

pass_context=True is from > 1.0

#

@bold oxide

bold oxide
#

oh

#

lemme remove and see

slate swan
#

Isn’t gonna make ur thing work

#

but why’re you using it?

bold oxide
#

I went scouring around trying to see if something could work

kindred epoch
slate swan
#

I'm making a counter bot what would be some good info to store in database

quiet coral
#

hello how can I change the activity of my bot to something like 'picking random stocks' with discord.py

kindred epoch
slate swan
#

I'm still doing it

kindred epoch
#

What

slate swan
#

What am I going to use if I don't use a database

kindred epoch
#

Nothing

#

Why do you need a db for a counting bot

slate swan
#

How would I get the current number

#

For multiple servers

#

And b able to tell the difference between each servers

kindred epoch
#

Can you elaborate on what ur bots gonna do

slate swan
#

Umm sure

#

It's going to join the server and someone will use the command Count! Create [goal number]

#

It will create a channel say Counting-[goal number]

#

And it will send a message like the goal is number let's do this

#

And they will count

#

And when they reach number it says congrats and I'll add some options for owner to tweak with

kindred epoch
#

Ok

#

First, store the channel id so you can isolate the counting to only be able tow work in that

slate swan
#

Ok

kindred epoch
#

I'm sure u know how to do something like that

slate swan
#

Mhm

kindred epoch
#

And then to get the last number, tell them to send something like end before sending the last number, then you can use wait_for to get the last number

slate swan
#

That makes sense to me

kindred epoch
#

Ok, try making that

slate swan
#

i need a temp mute command please

final iron
#

We don't spoon feed in this discord server

slate swan
#

i tried many commands

#

but nothing

shrewd pasture
#
      finished = discord.Embed(title="Versai Applications", description=f'Your Answer for Question 12: `{a10.content}`\nAre you sure you want to submit? Please react below!', color = discord.Colour.blue())
      print("first mark")
      msg = await ctx.author.send(embed=finished)
      await msg.add_reaction(checkmark)
      await msg.add_reaction(xmark)
      print("second mark")
      def check(reaction, user):
        print("3rd mark")
        return all((user.id==ctx.author.id, reaction.message.id==msg.id, str(reaction.emoji) in (checkmark, xmark)))
        print("4th mark")

      reaction = (await self.bot.wait_for('reaction_add', check=check))[0]
      if str(reaction.emoji) == checkmark:
        print("5th mark")

I get 0 errors and when i run it it gets to the 3rd mark before not working. Anyone know why? It works perfectly fine in the main server when someone runs it

slate swan
#

iirc yes

#

if i remember correctly

#

👍

boreal ravine
#

thats when your bot tries to do something it cant and yes

wintry panther
#

how to make bot not respond to dm

boreal ravine
#

hm

#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
boreal ravine
#

^

slate swan
boreal ravine
#

yes?

slate swan
#

my program uses requests to send an embed to discord webhook, how can I randomise the colour of the embed??

boreal ravine
#

just change the color?

slate swan
#

yup

boreal ravine
#

your sending the embed

slate swan
#

yup

boreal ravine
#

just change the color

slate swan
#

bruh

boreal ravine
#

hm

slate swan
#

i dont think it would work on requests

boreal ravine
#

wdym

#

show code

slate swan
#

i am on phone sorry so I dont have code

boreal ravine
#

hm

slate swan
#

but i am not using py em=discord.Embed()

wintry panther
boreal ravine
#

wait why are u using requests to send a webhook

slate swan
#

i am usingpy requests.post('webhook', json=data)

boreal ravine
#

hm

boreal ravine
slate swan
#

Json data for embed

boreal ravine
#

oh

#

cant u change that?

#

🗿

slate swan
#
{"embeds":[
{
"title":"test"}]}```

need to randomise colour
slate swan
boreal ravine
#

im saying

#

cant u change data to have a random color using discord.Color.random()

slate swan
#

i didn't tried but I don't think it would work but let me give it a try later

#

kek

boreal ravine
#

hm

slate swan
#

👍 thx

boreal ravine
#

👍

vale glen
#

DISCORD EMBEDSA/????? WOHA

boreal ravine
#

ok

supple thorn
#

what

kindred epoch
#

Uh

#

Send code

wintry panther
#

i use if message.content.startswith

boreal ravine
lyric moat
#

how can I make my bot mobile online custom status?

#

like this

boreal ravine
#

why is every bot named bender

boreal ravine
lyric moat
lyric moat
slate swan
slate swan
slate swan
boreal ravine
#

a bug