#discord-bots

1 messages · Page 1154 of 1

paper sluice
#
                if len(voice_client.channel.members) == 1:
                    await voice_client.move_to(channel)
                else:
                    raise DifferentVoiceException

to:

                if len(voice_client.channel.members) != 1:
                    raise DifferentVoiceException
                await voice_client.move_to(channel)
slate swan
paper sluice
#

its just a 1 to 1 replacement 🤷‍♂️

dusky pine
#

make your code readable, not shorter 😔

paper sluice
#
        if (voice := user.voice) and (channel := voice.channel):
            ...
        else:
            raise NoVoiceException

to:

        if not ((voice := user.voice) and (channel := voice.channel)):
            raise NoVoiceException
        ... 
slate swan
#
@classmethod
async def validate(cls, bot: Bot, iact: Interaction):
        if iact.guild is None: raise GuildOnlyException
        user = cast(Member, iact.user); voice_client = cast(Optional[Voice], iact.guild.voice_client)
        if (voice := user.voice) and (channel := voice.channel):
            if not voice_client: voice_client = await channel.connect(cls=Voice)
            elif channel != voice_client.channel:
                if len(voice_client.channel.members) == 1: await voice_client.move_to(channel)
                else: raise DifferentVoiceException
        raise: NoVoiceException; return cls(bot=bot, guild=iact.guild, voice_client=voice_ user=user, channel=cast(GuildMessageable, iact.channel), interaction=iact,)

because yes

cold sonnet
#

the fuck

#

does it only look bad on mobile

#

it looks horrible

paper sluice
#

basically try to invert your conditions

cloud dawn
#

hot

#

help

cold sonnet
#

cold

#

helped

cloud dawn
#

🙏

slate swan
cloud dawn
#

I made a pretty good function to handle voice connection.

vocal snow
#

pls send 🙏

vocal snow
cloud dawn
# vocal snow pls send 🙏

It's a custom class with inter so I can't really send it without sending the whole thing around 300 lines lol

#

I could send it to get the idea but you would need to make it work.

slate swan
vocal snow
#

my current voice connection thing is so messy

cloud dawn
# vocal snow yes thats fine
    async def connect(self, inter: Interaction, vc_opt: VoiceChannel | None = None, direct: bool = False) -> None:
        try:
            if self.voice_client is None or not self.voice_client.is_connected():
                channel = vc_opt or inter.user.voice.channel
                self.voice_client = await channel.connect(reconnect=True, timeout=None, self_deaf=True)
                if not direct:
                    return await inter.response.send_message(f"Connected to {channel.mention}.")

            raise ClientException
        except AttributeError:
            await inter.response.send_message("You are not connected to a voice channel.")
        except ClientException:
            if vc_opt:
                if vc_opt.id == self.voice_client.channel.id and self.voice_client.is_connected():
                    return await inter.response.send_message(f"I'm already connected to {vc_opt.mention}.")

                if self.voice_client.is_connected():
                    await self.voice_client.move_to(vc_opt)
                else:
                    await self.disconnect()
                    self.voice_client = await inter.user.voice.channel.connect(
                        reconnect=True, timeout=None, self_deaf=True)
                await inter.response.send_message(f"Connected to {vc_opt.mention}.")
            else:
                if not direct:
                    if self.voice_client.is_connected():
                        await inter.response.send_message("Already connected to a voice channel.")
                    else:
                        await self.disconnect()
                        self.voice_client = await inter.user.voice.channel.connect(
                            reconnect=True, timeout=None, self_deaf=True)
                        await inter.response.send_message(f"Connected to {inter.user.voice.channel.mention}.")
#

if vc_opt isn't passed it gets tries the author

vocal snow
#

Ah nice, ty :D

cloud dawn
#

Aka if it is passed it kinda works like move

cold sonnet
#

yknow what Ashley would say to this piece of code?

cloud dawn
vocal snow
slate swan
placid skiff
vocal snow
#

because 3.10+

cloud dawn
placid skiff
#

Rude

cold sonnet
#

genius

cloud dawn
#

I had lots of issues whit people forcibly disconnecting the bot from the vc.

rain olive
#

I feel like Hikari is underrated

cloud dawn
cloud dawn
#

And a less a mess of slash commands

cloud dawn
rain olive
rain olive
placid skiff
slate swan
cloud dawn
placid skiff
#

It's not skill issue if you're too lazy to do all that shit just for a command D_D

rain olive
#

you gotta understand if the API sucks, you cant expect better from wrappers

placid skiff
#

Like, why do we use API wrappers? cuz we're too lazy to create our owns, that's it, not because we won't be able to do them

cloud dawn
#

But I might consider using hikari tho since their restapi does look pretty 👌

rain olive
#

nah literally 99% of yall cant create ur own wrappers

slate swan
#

totally

cloud dawn
placid skiff
rain olive
#

tell that to the people that learn python solely for a discord bot

past lily
#

What a SyntaxError

past lily
#

tons

slate swan
#

Shocking.

rain olive
#

literally every person in d.py's help channels

slate swan
#

god

placid skiff
slate swan
#

They should know that you have to do what Hay does with Python.

rain olive
#

I use python to scare cobras

slate swan
#

I use python to make choccie.

placid skiff
vocal snow
placid skiff
#

we teach them both python and d.py here

slate swan
#

I use python to literally do nothing, cuz js FTW av_pepeexit

past lily
#

is dpy typed?

rain olive
slate swan
past lily
#

Haven’t used it in a while

slate swan
#

Yes teaching people is not a good thing.

placid skiff
rain olive
#

you really dont get my point do you jammy

vocal snow
rain olive
#

teaching people python via d.py is not a good thing imo

slate swan
#

That is not for you to judge, everyone learns in different ways.

rain olive
#

what part of "imo" did u miss sir

slate swan
#

I don't care.

cloud dawn
#

I think people should learn whatever they want tbf, and they won't listen anyways.

rain olive
#

wow so scary

vocal snow
#

!topic

#

no

slate swan
vocal snow
#

whats the one where it suggests a different topic

sour basalt
#
@spin.error
async def spin_error(ctx, error):
    if isinstance(error, MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error```
#

Not work

rain olive
#

what not work

sour basalt
#

not send message if you have alredy the role

rain olive
#

but u checked for MissingPerm

placid skiff
sour basalt
#

??? what his for this

cloud dawn
#

ts is my bb

sour basalt
#

what's the name of that for my code

#

@rain olive

placid skiff
slate swan
sour basalt
#

what should I check to see if user redo the command to receive the role already has it

past lily
#

When I write ts for webdev stuff it basically forces you to write correct code, and you don’t have to deal with any of the stupid js “features”

sour basalt
#

What i should do please

#
@spin.error
async def spin_error(ctx, error):
    if isinstance(error, MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error```
#

not send any message

cloud dawn
#

I'm using react ts I'm loving it.

placid skiff
cloud dawn
sour basalt
#

what is ternary

slate swan
#

dictionary exists

cloud dawn
slate swan
sour basalt
cloud dawn
#

Kinda like a switch.

past lily
sour basalt
#

its only a message

#

like a notice you already have the role

past lily
#

Have you used trpc?

placid skiff
cloud dawn
#

I hate js debugging :(

sour basalt
#
from discord.ext import commands
import discord
import asyncio
import random
import os

activity = discord.Activity(type=discord.ActivityType.watching, name="TelSpin")
bot = commands.Bot(
    command_prefix=commands.when_mentioned,
    activity=activity,
    status=discord.Status.idle,
    intents=discord.Intents.default(),
)

@bot.command(aliases = ["telspin"])
async def spin(ctx):
    await ctx.author.add_roles(ctx.guild.get_role(998247663441031178))

@spin.error
async def spin_error(ctx, error):
    if isinstance(error, MissingPermissions):
        embed = discord.Embed(
            title="TelSpin Role Error",
            description=f"you have alredy the role",
            colour=0xF42222,
        )
        await ctx.send(embed=embed)
    else:
         raise error```
#

All my code i want work spin error but not work

slate swan
past lily
#

Guess why the riir meme exists, is because people actually rewrite their code to make it easier to work with

past lily
#

I don’t know your situation, but it might be worth it to switch

#

The majority of my errors building web stuff is with css

cloud dawn
#

How to center a div

past lily
#

idk

placid skiff
#

No one does

slate swan
#

long time no see

paper sluice
#

ello 👋

slate swan
#

Hi Ryuga, hope u still remember me

#

lmao

#

anyways i wanted to ask.. just like how bot can read messages... can bot also read the slash command used?

#

despite of the fact whether the slash is of its own or the other bot

cloud dawn
slate swan
#

that . at the end makes you scary 😔

paper sluice
cloud dawn
#

Unless that bot sends a message response.

slate swan
#

owo alr alr Panda

#

makes sense

cloud dawn
unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.

New in version 2.0.
cloud dawn
#

"Called when an interaction happened."

#

So includes button presses, drop menu etc.

slate swan
#

@slate swan NM_peepoUwU

robust fulcrum
#

Hi

slate swan
#

send friend req on this account too

#

kekw

#

kek diff accounts?

austere gust
#

Hey

#

How can I ban without using ctx? Because I am using on_message, and I can't use ctx there if I am right

tacit storm
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
austere gust
#

I tried by this way, but isn't really working

slate swan
#

my bot is not sending anything at all

import discord, os
from discord.ext import commands
from discord.ui import Button

bot = commands.Bot(command_prefix="h!")

@bot.event
async def on_ready():
  print("Logged in")

@bot.command()
async def h(ctx):
  ctx.reply("hey")

bot.run(os.environ['Token'])
#

i typed h!h

#

no reply at all

#

no errors too][

cold sonnet
#

it's

#

await ctx.respond("hey")

glad cradle
#

await ctx.reply it's for disnake

slate swan
robust fulcrum
#

Is there any alternative for perrespective api?

slate swan
#

idk why I wrote that kek dont sue me

slate swan
slate swan
vocal snow
slate swan
paper sluice
vocal snow
#

thats perspective not perrespective

paper sluice
#

oh 💀

vocal snow
slate swan
#

how to send a message when button is clicked

slate swan
slate swan
slate swan
slate swan
vocal snow
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
vocal snow
#

interaction.response.send_message in the button callback

slate swan
# slate swan discord.ui
@discord.ui.button(...)
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
  await interaction.response.send("uwu")
#

just see the examples ASakashrug

#

ooh

slate swan
#

it's optional, so are the typehints

#

but okay.

#

ohh

jaunty isle
#

Hey so I was building a discord bot for a community i am a part of and i recently heard that slash commands are being made compulsory for all bots.. Is it going to be easier to continue with discord.py and develop /commands or is it better to switch to hikari

vocal snow
glad cradle
#

I want to make an avatar command that shows the avatar of multiple users having as input a list of members, i want to display all the avatars with a paginator, how could I store the list of embed? Should I create a cache?

vocal snow
#

what are you going to store?

glad cradle
dull knot
#

Question.

When we type ?dm @user (input text)

The @user and input text are called parameters, right?

slate swan
vocal snow
#

especially since the member list will be variable

dull knot
glad cradle
#

a list is better

robust fulcrum
dull knot
robust fulcrum
#

They not sent me mail from 3 days

vocal snow
slate swan
real grail
#

I want to make the bot send a notification when there is a problem with the network, here is what I tried to do

@tasks.loop()
async def wifi(developer):
    try:
        https = urllib3.PoolManager()
        request = https.request("GET", "https://google.com/")

    except:
        print(Fore.RED + f"[ERROR] Network interrupts. Check your network connection.")

        dm = discord.Embed(
            description = f":no_bell: **Сетевые прерывания.** Проверьте состояние системы.",
            colour = discord.Colour.red()
        )

        await developer.send(embed = dm)```
*The function is run from the on_ready event
slate swan
robust fulcrum
glad cradle
robust fulcrum
slate swan
#

so im making a badwords filter. This is how i did it

msg = "https://twitter.com/RLEsports/status/1541692683034497030twat"
with open('BadWords.txt', 'r') as f:
    words = f.read()
    badwords = words.split()
    for word in badwords:
        if word in msg:
            print(f"found {word}")

and the output is

found u
found c
found u
found c
found e
found r
found twat

why does it find this letters as bad words.

dull knot
vocal snow
#

and a variable to keep track of the current page index

glad cradle
slate swan
#

ASakashrug what's to learn in that

robust fulcrum
vocal snow
dull knot
#

Anyways, thxChikaThumbsUp

slate swan
glad cradle
vocal snow
#

self.items = []

#

in the view init

#

then you can use self.items in the other view methods (namely the button callbacks, which you'll be using to control the pagination)

glad cradle
vocal snow
#

class Paginator(View):
    def __init__(self, users: list[User]):
        self.items = [Embed().set_image(url=user.avatar.url) for user in users]

``` is how i'm imagining it
glad cradle
#

me too but

vocal snow
#

how would that happen?

glad cradle
#

in my previous version this happened

vocal snow
#

if you used this same code, that's pretty much impossible

#

unless you passed the same list of users to it, of course

glad cradle
#

wait I'll search the previous version

cerulean solstice
#
import discord
from discord.ext import commands, tasks
import youtube_dl

from random import choice

client = commands.Bot(command_prefix='.')

status = ['Quality Music', 'Music For You']

@client.event
async def on_ready():
  change_status.start()
  print('Bot is online!')

  @tasks.loop(seconds=20)
  async def change_status():
    await client.change_presence(activity=discord.Game(choice(status)))

client.run('Token')
vocal snow
vocal snow
vocal snow
cerulean solstice
glad cradle
vocal snow
#

sure

cerulean solstice
glad cradle
vocal snow
slate swan
vocal snow
cerulean solstice
#

and fix that error?

slate swan
# vocal snow btw, discord has a new automod feature

no im making something with modals. So i dont want the users entering this words in the modal. So i wanted to implement the filter. Im just making it separated from the main so i can test it, cuz it seems like it doesnt work good

cerulean solstice
slate swan
#

oh

vocal snow
slate swan
vocal snow
#

bad = {"words", "here"}

text = set("user text here".split())

if caught := bad & text:
    await ctx.send(f"You can't use these word(s)!: {', '.join(caught)}")
cold sonnet
#

is that how := works

vocal snow
#

yep

#

ever since i started using strict typechecking ive been using it like crazy

#
        if (app := self.bot.application) and (team := app.team) and iact.user not in team.members:
            return await iact.response.send_message("This command is owner-only!")
cold sonnet
#
        if self.bot.application and app.team and iact.user not in team.members:
            return await iact.response.send_message("This command is owner-only!")
#

oh wait no

vocal snow
#

no, app is not defined and neither is team

cold sonnet
#

lol

#

but why did you need it above

vocal snow
#

could've been ```py
iact.user not in self.bot.application.team.members:

vocal snow
#

I blame andy for this mess honestly

cold sonnet
#

wait that's not really my question in the code above

#

!e

bad = {"words", "here"}

text = set("user text here".split())

if caught := bad & text:
    print(f"You can't use these word(s)!: {', '.join(caught)}")
vocal snow
#

edit to print

unkempt canyonBOT
#

@cold sonnet :white_check_mark: Your eval job has completed with return code 0.

You can't use these word(s)!: here
cold sonnet
#

what does & do

vocal snow
#

set intersection

#

gives you the common elements

cold sonnet
#

I understood

shrewd apex
spare urchin
#

i wanna know if there is some way to add attachment option in slash commands ( nextcord )

paper sluice
#

!d nextcord.Attachment

unkempt canyonBOT
#

class nextcord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") and is hashable.
paper sluice
#

type hint with that ^

cerulean solstice
#

hey um
How do we make a command an embed for example

await ctx.send('Test*:1564badgedeveloper:')

how can i make this message an embed?

paper sluice
#

!d discord.Embed you make an embed using this

unkempt canyonBOT
#

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

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

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

New in version 2.0.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
cerulean solstice
shy vault
#

does anyone have a streaming bot status loop command?

slate swan
#

exactly do you need help with

shy vault
# slate swan what

i need help with my status loop command, instead of streaming it says listening even tho its set to streaming

shy vault
# slate swan code
async def statusloop():
  await client.wait_until_ready()
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=f";help"))
  await sleep(3)
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=f"over {len(client.guilds)} guilds"))
  await sleep(3)
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=f"over {len(set(client.get_all_members()))} members"))
  await sleep(3)
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.streaming, name=f"/kamado"))
  await sleep(3)
statusloop.start() ```
pliant gulch
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.

slate swan
#

nice task btw

#

yes.

shy vault
slate swan
#

sarcastic it was

shy vault
vocal snow
#

I rewrote everything with annotations!

pliant gulch
vocal snow
#

Not sure if I typed correctly but there are only 2 ignores!

pliant gulch
#

Inb4 half of the typehints are Any

vocal snow
cold tide
#

Can someone tell me why this isnt working?

#

async def tt(ctx): if ctx.channel.id=="998759012889809046": embed=discord.Embed() embed=discord Embed(title="Reaper Gen ! 🤖",description="Command Online !",color=0xffff00) embed.add_field(name="Generated Info:",value=random.choice(tiktok),inline=True) embed.set_footer(text="Gen Command ! Dev - vd#7157") await ctx.reply(f"Successful Generation, check your dms {ctx.author} ! 🤖") await ctx.author.send(embed=embed)

#

cant use indentation on my device

slate swan
slate swan
cold tide
#

Ahh okay thankyou!!

slate swan
cold sonnet
#
        embed=discord.Embed()
        embed=discord
        Embed(title="Reaper Gen ! 🤖",description="Command Online !",color=0xffff00)
```?
dull knot
#
bot.listen()
async def on_member_join(member):
 member.guild.get_channel(984905609025556541)
 embed = disnake.Embed(
    title="Welcome to Ani-Nation! <a![YC](https://cdn.discordapp.com/emojis/996598948951248896.webp?size=128 "YC")996598948951248896>",
    description="""**Visit these channels!**: <a![NT](https://cdn.discordapp.com/emojis/996588620188229642.webp?size=128 "NT")996588620188229642>
<a![PA0](https://cdn.discordapp.com/emojis/998368055723819051.webp?size=128 "PA0")998368055723819051><a![PW](https://cdn.discordapp.com/emojis/993662583829704754.webp?size=128 "PW")993662583829704754>[Network](https://discord.com/channels/943462265317912576/959345468557643807/)<a![PW](https://cdn.discordapp.com/emojis/993662583829704754.webp?size=128 "PW")993662583829704754>
╭<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Guidelines](https://discord.com/channels/943462265317912576/943462265317912579)<a![HC](https://cdn.discordapp.com/emojis/996587566008639578.webp?size=128 "HC")996587566008639578>
├<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Roles](https://discord.com/channels/943462265317912576/987446939534655498)<a![PN](https://cdn.discordapp.com/emojis/996588276070752266.webp?size=128 "PN")996588276070752266>[Intro](https://discord.com/channels/943462265317912576/953106759235555428)<a![YB](https://cdn.discordapp.com/emojis/996598060404719706.webp?size=128 "YB")996598060404719706>
╰<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Leveling System](https://discord.com/channels/943462265317912576/953107383519957012)<a![TC](https://cdn.discordapp.com/emojis/996592791104794684.webp?size=128 "TC")996592791104794684>""",
    colour=disnake.Colour.random(),
url="https://discord.com/channels/943462265317912576/953113946930438185/"
 )

 embed.set_thumbnail(url=f"{member.author.display_avatar}")
 await member.send("**<@&971468441682870332> Greetings, {member.mention}**", embed=embed)

It doesn't send to the specified channel for some reason. Any help?.

#

I'm using disnake btw

vocal snow
#

it's not sending to the member dm?

#

do you have member intents enabled?

ionic turtle
real grail
#

How to implement command to clear messages from bot in dm with bot?

paper sluice
#

and to check if channel is a dm, you can do isinstance(channel, discord.DMChannel)

real grail
vale wing
#

What

short stump
#

how to find the variable of the user who added the bot to the server? needed for logs

quaint epoch
#

I sent you an answer in general

short stump
#

I'm just just starting to learn how what and where works in discord.py

grizzled geyser
#

Hey guys, I need an advice there, so I'm launching my bot for my discord server, I want to create a kind a " replication channel " that takes a message coming from a unique channel, and depending if python can find one of the strings that I gave him in my message, he sends that message to a specific channel. ( take a look at the code ) So that works but now I'd like to automatize this code because its repetitive and dirty ! So I started listing the names that I wanted python to find, but there I'm stuck I dunno what to do, I'd like him to compute a n+1 function that will make a 'check' for every name I made, is that possible ? I'm sending the code right now ! Thanks

#

Ok so this is my code right now

#

And I would like him to achieve this kind of result :

tired hinge
sick birch
# grizzled geyser

It'd be best to create a triggerword-ID mapping, and use that instead. You can eliminate the if chain entirely

sick birch
# real grail help

ctx.author.id will return the ID of the person who invoked the command

real grail
#

._.

#

I need to somehow get the id of the dm channel with the author of the command

sick birch
#

DM channels don't have IDs

#

The person you have the DM with does, which is what I assumed you were asking

real grail
#

I need to make a command that will clear messages from the bot in the author's dm

real grail
#

I don't understand how to get channel

sick birch
#

You don't need to, I believe discord.Member and discord.User subclass discord.Messageable in one way or another

real grail
#

And... ?

sick birch
#

And you don't need to get the channel, because the discord.Member object is the channel

#

it has many of the methods that other discord.Messageables have, such as fetch_message and history() (which is what you're looking for)

warped mirage
#

guys

#

i know how to do slash commands in main.py , how can i setup in a cog?

real grail
#

for message in ctx.author.history(limit = quantity):?

sick birch
real grail
sick birch
dire folio
#

The .jpg should be lowercase

#

Try changing both of them to .jpg

vocal snow
#

Try Arial.ttf

shrewd apex
#

i think pil has a default font

#

u don't even need font tbh

#

those are emojis not images

#

🇦

#

🇦

#
🇦 
#

it's regional indicator

#

regional_indicator_a

#

just add : on both sides

#

yeah and the font= also

shrewd apex
#

then add : on left and right of that

#

and send

#

\🇦

#

see

left idol
#

do people tend to make bots on discord.py or pycord?

quaint epoch
left idol
#

why didn't i think of that

sick birch
#

It's just the same way you would on discord?

#

h 👏 i

maiden fable
#

!e

text = "Hi!"
print("👏".join(text))
unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

H👏i👏!
maiden fable
#

!join

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
maiden fable
#

!e

text = "Hi!"
print(" ".join(text))
unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

H i !
maiden fable
#

So

#

I mean, that is right

#

Excluding the weird iPhone quotes

vocal snow
#

Rich people quotes

maiden fable
#

Yes

#

That is why they speak s t y l e

sick birch
#

He did say excluding the iPhone quotes

#

Quotes that look like quotes but aren't really quotes

#

iPhone uses them

#

“ “ vs " "

#

The latter is the proper quotes, the former is the iPhone quotes

hardy yoke
sick birch
radiant junco
#

How would I use requests to interact with bot interactions from a Discord bot?

sick birch
#

No, unless you're making subcommands

radiant junco
#

I've tried

def interact(guild_id, message_id, component_id):
  global channel_id, bot_id
  json = {
    'type': 3,
    'guild_id': guild_id,
    'channel_id': channel_id,
    'message_id': message_id,
    'application_id': bot_id,
    'data': {
      'component_type': 2,
      'custom_id': component_id
    }
  }
  headers = {'Authorization': os.environ['AUTH']}
  request = requests.post('https://discord.com/api/v9/interactions', headers=headers, json=json)
  print(request.json())
sick birch
#

I know it's not possible

#

It doesn't pass the slash command validation regex

#

Can I see an example?

#

I believe that's an argument, not part of the command name

#

The command name is just text

#

^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ the slash command validation regex

#

Just create a regular slash command with regular arguments. Nothing special

slate swan
#
@client.command(case_insensitive=True)
@commands.has_permissions(administrator=True)
async def mute(ctx, member: discord.Member, *, reason=None):
  if reason == None:
    await ctx.send('Please write reason!')
    return
  guild = ctx.guild
  muteRole = discord.untils.get(guild.roles, name = "Muted")

  if not muteRole:
    await ctx.send("No Mute Role Found!")
    muteRole = await guild.create_role(name = "Muted")

    for channel in guild.channels:
      await channel.set_permissions(muteRole, speak=False, send_messages=None, read_messages=True, read_message_history=True)
    await member.add_roles(muteRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted in {ctx.guild} | Reason: {reason}")
    await member.send(f"You have been muted in {ctx.guild} | Reason: {reason}")

@client.command(case_insensitive=True)
async def unmute(ctx, member: discord.Member, *, reason=None):

  guild = ctx.guild
  muteRole = discord.untils.get(guild.roles, name = "Muted")

  if not muteRole:
    await ctx.send(f"coś")
    return
  await member.remove_roles(muteRole, reason=reason)
  await ctx.send("unmuted")```
#

why it isn't working - how to fix it?

radiant junco
#

you spelled utils wrong

#

untils instead of utils

unkempt canyonBOT
#

examples/app_commands/basic.py lines 47 to 54

@client.tree.command()
@app_commands.describe(
    first_value='The first value you want to add something to',
    second_value='The value you want to add to the first value',
)
async def add(interaction: discord.Interaction, first_value: int, second_value: int):
    """Adds two numbers together."""
    await interaction.response.send_message(f'{first_value} + {second_value} = {first_value + second_value}')```
slate swan
#

oh

hushed galleon
#

that definitely is a subcommand, the same bot has other commands starting with /text as well

sick birch
#

Ah

#

In that case my apologies, I can't help with slash commands in pycord

slate swan
radiant junco
slate swan
#
@client.command(case_insensitive=True)
@commands.has_permissions(administrator=True)
async def mute(ctx, member: discord.Member, *, reason=None):
  if reason == None:
    await ctx.send('Please write reason!')
    return
  guild = ctx.guild
  muteRole = discord.utils.get(guild.roles, name = "Muted")

  if not muteRole:
    await ctx.send("No Mute Role Found!")
    muteRole = await guild.create_role(name = "Muted")

    for channel in guild.channels:
      await channel.set_permissions(muteRole, speak=False, send_messages=None, read_messages=True, read_message_history=True)
    await member.add_roles(muteRole, reason=reason)
    await ctx.send(f"{member.mention} has been muted in {ctx.guild} | Reason: {reason}")
    await member.send(f"You have been muted in {ctx.guild} | Reason: {reason}")
#

why this mute command no working?

#

(any errors)

#

@sick birch 😄

sick birch
sick birch
slate swan
sick birch
#

No. Only create the role if it doesn't exist. If it does exist, just apply it

#

Right now if the role already exists, your code does nothing

slate swan
#

thank you bro working ❤️

#

@sick birch there is one problem. If the role is missing, it sends information that the role was not found and creates it and then mutates it. If the roe is already there, the mute command does not work

sick birch
#

That's what I said, yes. If the role is already there your code won't do anything

#

Mainly because of this part:

if not muteRole:
  ...
#

If muteRole is a truthy value (it exists), the not inverts it, and is now False which means the if statement won't run

slate swan
#

how to fix it?

sick birch
#

Create an if/else statement that handles if the role exists or not

slate swan
#

uhh i don't know how

sick birch
#
mute_role = discord.utils.get(...)
if mute_role:
  # just assign the role to the user
else:
  # create the role, and then assign
exotic maple
#

Hey how do i get the i['role'] mentioned here?

sick birch
#

Alternatively...

mute_role = discord.utils.get(...)
if not mute_role:
  mute_role = await guild.create_role(...)

# assign mute_role to the user as normal
slate swan
#

I don't know if you got me right

exotic maple
#

maybe*

sick birch
slate swan
#

My point is that if there is no such role, it will create it and give it muta, but if there is such a role, the command does not work

exotic maple
gusty shard
#
@bot.command()
async def invites(ctx):
    totalInvites = 0
    for i in await ctx.guild.invites():
        if i.inviter == ctx.author:
            totalInvites += i.uses
    await ctx.send(f"You've invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the server!")```
#

i found that code on stackoverflow, how can i make it send it to a channel when somebody joins with on_member_join

exotic maple
gusty shard
#

yep

#

i tried making it but i dont know where to start

sick birch
fathom lark
sick birch
#

You've just entered the python repl, you can exit using exit()

#

like so

fathom lark
#

thanks

whole sparrow
#

Is anyone here whos good at beautifulSoup4 I wont start a help as its not discord related ig here I just want advice privately if possible im stuck on an issue for my discord bot

fathom lark
#

There is a command handler in python?

tidal hawk
#

How hard is it to connect Discord py bots with websites? For instance if somebody clicks a button website, then the discord bot will acknowledge

sick birch
tidal hawk
#

Okay

nimble kindle
#

ok so im watching ep 3 of a yt named lucas
and he completly switched files or something
now hes importing lightbulb
do i need to make another py file and write the lightbulb code?
or what

#

im using hikari btw

hardy yoke
nimble kindle
granite matrix
#
@commands.command()
async def eval(self, ctx, *, code):
    exec(code)

how to add timeout for that? for example, if i do 5**5**5**5, function stops after 3 seconds?
i have tried a lot of things from stackoverflow, but they don't work

quaint epoch
#

See snekbox

granite matrix
#

ye, saw that, but it must be launched by me to use, yes? im lazy to do that)

#

oh, found how to use without web server, going to try it

gusty shard
#

how can i find a member from his name on my server

#

can you send me a simple example please?

#

im searching it for 30min

#

and i dont even have any idea about how to code it

granite matrix
#

!d discord.ext.commands.MemberConverter
(you can use that)

unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
blazing kettle
#

my error handling works but my 1 command just stops working

left idol
#

currently my bot is written in pycord, if i want to switch to discord.py is there a significant amount i would have to change?

hardy yoke
whole sparrow
#

how do i make a seperate on_ready function that does a specific function once bot runs

hardy yoke
left idol
whole sparrow
#

How do I make a background task that repeats every 5 minutes and does a specific function

hardy yoke
whole sparrow
#

and also this background task runs as soon as the bot runs

whole sparrow
hardy yoke
whole sparrow
#

Im using disnake

hardy yoke
#

good example there

whole sparrow
#

ahhh thanks homie

whole sparrow
sick birch
nimble kindle
sick birch
#

Most of them on YouTube aren't, to be honest. Which is unfortunate but that's just how things are. You'll find a lot of resources in the pinned messages of this channel

nimble kindle
nimble kindle
#

can i dm you or just chat in here

sick birch
#

You'd find better help in the discord.js server then

#

We only really help with python libraries here

nimble kindle
#

yea ik i was asking if you knew anyone who makes good js tutorials

wise gull
#

somebody knows how to make bot that plays music from yt?

white aurora
#

tos

sick birch
lofty aspen
#

Anyone know why my code isn't working?

import disnake
from disnake.ext import commands
import os

DISALLOWED_SYMBOLS = ["|", "#", "$", "~", "`"]
REACTION_EMOJIs = ["26A0 FE0F"]
# TODO Automatic Database Creation
# TODO PEP8 Compliance
intents = disnake.Intents.all()
bot = commands.InteractionBot(intents=intents)


@bot.event
async def on_message(message):
    first_opening_bracket, first_closing_bracket = message.content.find("["), message.content.find("]")
    if str(message.content.lower()[first_opening_bracket:first_closing_bracket]) in DISALLOWED_SYMBOLS:
        await message.channel.send("Please do not use symbols in the TW. Please Edit the message", ephemeral=True)

It's meant to send that if any of the list contents in the const DISALLOWED_SYMBOLS are in the indexes of first_opening_bracket and first_closing_bracket.

lofty aspen
#

nvm fixed it

whole sparrow
#

how do i find the easy way to get an emojis thing so i can put it in my discord bot

#

i forgot how to

#

how do i send emojis in my discord bot

jolly rock
#

You would do \:emojiname:

#

So for example

#

Above is emoji id

#

And below is emoji

runic saddle
#

keep getting irrelevent error

paper sluice
#

its Bot not bot

#

from discord.ext.commands import Bot

slate swan
#

why are you running files in the discord.py source code

runic saddle
paper sluice
#

you shouldn't make files and run it in the source code

#

just make a file in some other directory outside and run your code there

runic saddle
#

ah, thanks , i'll try that. I wasn't aware that running example files within the source code was frowned upon.. I thought it would still work

dull knot
#
@bot.listen()
async def on_member_join(self, member):
 guild = member.guild
 
 if guild.system_channel is not None:
   embed = disnake.Embed(
    title="Welcome to Ani-Nation! <a![YC](https://cdn.discordapp.com/emojis/996598948951248896.webp?size=128 "YC")996598948951248896>",
    description="""**Visit these channels!**: <a![NT](https://cdn.discordapp.com/emojis/996588620188229642.webp?size=128 "NT")996588620188229642>
<a![PA0](https://cdn.discordapp.com/emojis/998368055723819051.webp?size=128 "PA0")998368055723819051><a![PW](https://cdn.discordapp.com/emojis/993662583829704754.webp?size=128 "PW")993662583829704754>[Network](https://discord.com/channels/943462265317912576/959345468557643807/)<a![PW](https://cdn.discordapp.com/emojis/993662583829704754.webp?size=128 "PW")993662583829704754>
╭<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Guidelines](https://discord.com/channels/943462265317912576/943462265317912579)<a![HC](https://cdn.discordapp.com/emojis/996587566008639578.webp?size=128 "HC")996587566008639578>
├<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Roles](https://discord.com/channels/943462265317912576/987446939534655498)<a![PN](https://cdn.discordapp.com/emojis/996588276070752266.webp?size=128 "PN")996588276070752266>[Intro](https://discord.com/channels/943462265317912576/953106759235555428)<a![YB](https://cdn.discordapp.com/emojis/996598060404719706.webp?size=128 "YB")996598060404719706>
╰<a![S1](https://cdn.discordapp.com/emojis/993444719155748864.webp?size=128 "S1")993444719155748864>[Leveling System](https://discord.com/channels/943462265317912576/953107383519957012)<a![TC](https://cdn.discordapp.com/emojis/996592791104794684.webp?size=128 "TC")996592791104794684>""",
    colour=disnake.Colour.random(),
url="https://discord.com/channels/943462265317912576/953113946930438185/"
 )

 embed.set_thumbnail(url=f"{member.author.display_avatar}")

 await guild.system_channel.send("**<@&971468441682870332> Greetings, {member.mention}**", embed=embed)

I'm making a welcomer bot using the disnake library and the @bot.listen's on_member_join listener but it doesn't send the welcome embed on member join.

Intents in the Developer portal are enabled

#

It doesn't show any errors when ran

paper sluice
#

does the guild where you are testing have a system_channel

dull knot
#

Yup

#

It's also sending those built-on welcome msgs on that system channel

paper sluice
#

do you have an error handler?

dull knot
#

Error handler?

paper sluice
dull knot
#

Nope

dapper cobalt
dull knot
#

Still haven't learned cogs yet

paper sluice
dull knot
#

Oh.

dapper cobalt
dull knot
#

Let me try removing that

dapper cobalt
#

I was a little confused why is it bot.listen and has self?

dull knot
#

I'm kinda new so, lol. My bad

#

Still didn't work

dull knot
slate swan
dapper cobalt
slate swan
dapper cobalt
slate swan
#

im jokingpithink

dapper cobalt
slate swan
#

anyways hows that modeling career of yours😳

vocal snow
#

Good morning

slate swan
jolly basalt
#

so um

#

await ctx.send() returns discord.message.Message

#

but i need to get the message id from there

placid skiff
#

message = await ctx.send() \ print(message.id)

jolly basalt
#

oo ty

glossy edge
#

Hey guys, I want to capture my local FM radio audio and stream it to my music bot, how can i achieve something like that?

slate swan
#

im having problems

slate swan
#

That's very unfortunate.

If you don't give any information on what your problem is, you will keep on having the same problem.

#

Guys what is the command to install discord.py via pip ? i know this pip install -U discord.py but it didn't install the latest version.

#

There was some command with github.

#

thanks

slate swan
placid skiff
#

Someone knows how to convert a string which is a byte to a byte? (essentially i have "b'byte_like_object'" and i need b'byte_like_object')

paper sluice
#

ast.literal_eval?

placid skiff
#

Yup that worked

slate swan
#

you cant send a response to another channel
but you can defer the response and send a normal message in the other channel instead

slate swan
slate swan
#

what part.

robust fulcrum
slate swan
robust fulcrum
#

Ok

slate swan
#

!d discord.InteractionResponse.defer defer the response

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
robust fulcrum
#

Btw you should not send face reveal

slate swan
#

!d discord.TextChannel.send send to other channel

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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/latest/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.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/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/latest/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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

you can't set textinput fields for name and description of a modal

#

!d nextcord.ui.Modal

unkempt canyonBOT
#

class nextcord.ui.Modal(title, *, timeout=None, custom_id=..., auto_defer=True)```
Represents a Discord modal popup.

This object must be inherited to create a modal within Discord.

New in version 2.0.
slate swan
#

there's just title

slate swan
#

because thats the object

#

you should be using self.name.value & self.description.value

kind wind
#

how can you get the value of the message so it can edit the slowmode of the channel?

vocal snow
#

it's content?

kind wind
#

the int

slate swan
#

i think a command argument

#

are you using on_message to make the command? @kind wind

kind wind
#

i found just this on the docs

#

!d discord.TextChannel.slowmode_delay

unkempt canyonBOT
slate swan
#

i'm talking about how you're making the command, not what method you use to edit the slowmode

kind wind
#

yes

#

to edit the slowmode through a bot command

slate swan
#

what;s your current code?

kind wind
#

i tried doing something like this:

@bot.command()
@mods_or_owner()
async def slowmode(ctx, arg1):
    await discord.TextChannel.slowmode_delay(arg1)
slate swan
#

you need to typehint the arg1 argument to int,

#

and slowmode_delay is a property not a method

kind wind
#

so its something like (ctx, int)?

slate swan
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
slate swan
#

you need to pass slowmode_delay= arg1 in this

slate swan
kind wind
#

so, (ctx, arg1=int)

#

im sorry my language is greek and im trying to understand what it means

slate swan
worn tiger
slate swan
#

you can read more about it here

slate swan
vocal snow
kind wind
#

wait does slowmode_delay goes on * or on the **options

slate swan
#

you just channel.edit(slowmode_delay=...)

worn tiger
#

Oh lol wrong chat but thanks

kind wind
# slate swan you just `channel.edit(slowmode_delay=...)`

this?

@bot.command()
@mods_or_owner()
async def slowmode(ctx, arg1: int):
    edit = discord.TextChannel.edit
    await edit(slowmode_delay=arg1, reason="Slowmode command executed!")
    await ctx.reply("Set channel's slowmode to " + arg1 + " seconds!")
slate swan
#

nope, you use that method on an instance not the class itself

#
  • you can't add a string to an int, consider using f strings or convert arg1 to a str
#

because you can't send a ephemeral message, only responses can be ephemeral

kind wind
#

ive put it outside of the text string

slate swan
#

thats not a response

#

you send responses using .response.send_message

slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: can only concatenate str (not "int") to str
slate swan
#

!e ```py
print(f"string {1}")
print("string" + str(1))

unkempt canyonBOT
#

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

001 | string 1
002 | string1
slate swan
#

you can choose one of these ways

kind wind
#

so its this way:

print("test" + str(arg1)) 
placid skiff
#

use f-strings

kind wind
#

!e

arg1 = 12
print("number is " + str(arg1))
slate swan
#

yes

cold sonnet
#

user = ids

#

ids = ...

#

those are two useless variables, also int object has no attribute send

#

I'm an hour late

#

cuz of school

#

and a useless function sendmp

#

with two unnecessary args

#

and the useless response var

hybrid fjord
#

i can use a slash command in a channel (with application commands enabled) but my members can't. anything else that could be affecting it?

jolly basalt
#

so um, can i check if a specific user is using a specific bot

hybrid fjord
#

don't worry. found out one of the roles had a permission denied which i wasn't aware of

rain olive
slate swan
#

await reaction.remove(user) any who know why this dont work on event on_reaction_add

placid skiff
#

!d discord.Message.clear_reaction

unkempt canyonBOT
#

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

Clears a specific reaction from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.

New in version 1.3.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
placid skiff
#

!d discord.Message.remove_reaction or this one

unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.

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

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
hushed galleon
slate swan
#

member.icon.url for member’s icon url?

robust fulcrum
#

How can I use a listener in cogs?

polar granite
slate swan
#

Need a tutorial from basics

modest wagon
#

someone can drop the discord server in PM.

paper sluice
#

for?

slate swan
modern fiber
#

I made the basic DM command, can I make it so the DM from other party gets sent in the channel?

#

Basically so bot gets and sends the DM that it got from user that got DMed

paper sluice
#

👍

paper sluice
#

wdym by not working, it doesn't send the image or is the image not made?

placid skiff
unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
paper sluice
#

if you don't get any errors in your terminal, you probably have a faulty error handler

#

ok, u didnt write the condition for when member is not None

#

just dedent the stuff under member = ...

slate swan
#

dedent

#

why dont people use "unindent" 😔

paper sluice
velvet compass
#

dent-left

#

and dent-right

paper sluice
#

bruh 💀

slate swan
#

brad Superman

velvet compass
#

Hello

paper sluice
#

vip > and vip <

slate swan
#

go befriend the aliens, we are humans 2124_MikeSullyFaceSwap

#

okay not humans

#

but you get the idea

#

I'm so cringy

paper sluice
velvet compass
#

lol

slate swan
#

somebody teach me geometry pepecri

paper sluice
#

brad will teach you

#

he was making a dyson sphere 3 hrs ago

slate swan
#

more like it has too much

#

In my book they are of 3 types

#

okay Sparky.

paper sluice
slate swan
#

No

#

History sucks

paper sluice
#

i meant geometry but ok

slate swan
#

Uh

#

I thought geo graphy

slate swan
#

especially isosceles properties pepe_exit

paper sluice
#

dude

#

i did that like 4 years ago

#

probably 5

slate swan
#

okay.

slate swan
modern fiber
#

Can someone help?

#

I did pip install discord.ui multiple times

paper sluice
slate swan
paper sluice
slate swan
#

👋

shrewd apex
#

👋

dusky pine
#

all you need

slate swan
#

Hi nae nae

#

Hi asher

dusky pine
#

hello brocken pfp man

shrewd apex
#

it's still easy at first then it gets slightly tougher with vectors

#

sup sparky

slate swan
#

I have my exams starting a day after tmrw

#

And I'm playing minecraft 💀

modern fiber
#

anything else?

#

What do I do..

slate swan
#

oh

#

dont name your variable as all since all is an inbuilt python function

modern fiber
#

How do I name it then

slate swan
#

anything other than all

modern fiber
#

for some reason, since bot uses slash, I didnt have to state anything of that

#

not even prefix, but now it doesnt work without it

slate swan
#

what

#

...?

modern fiber
#

how do I define intents again..

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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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
#

My school book 💀

#

I was turning pages and I found this

modern fiber
#

where i can paste my code, so you can see? please

#

I dont know whats wrong

slate swan
#

!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.

modern fiber
#

Now it says this

slate swan
modern fiber
slate swan
#

Nice

modern fiber
#

its not nice bruh

#

XD

slate swan
#

def __init__ in the first place, and just add intents=discord.Intents.default() or whatever intents your require in the Bot constructor

#

Also

#

ur using client inside the subclass

#

and its define after it

modern fiber
#

What else did you said

slate swan
#

Codempls

#

Code pls*

modern fiber
slate swan
modern fiber
#

Oh,

#

I didn't updated

modern fiber
slate swan
modern fiber
slate swan
#

It changes link when you save

#

Wait no

#

Nvmd

#

def __init__

#

when

#

and why defining same parameters again

cold sonnet
#

on_ready changing presence

slate swan
#

Nyeah

#

Don't do it

#

Just define the class

#

A = Bot()

modern fiber
#

Bruh Im confused

slate swan
#

init takes no parameters

#

I dont understand why people dont learn OOP before starting discord.py, pisses me off

slate swan
modern fiber
#

what should I change smh

slate swan
modern fiber
#

im stupid and my brain is not working atm

cold sonnet
#

and what for subclass if you don't use it

slate swan
#

u dont have knowledge about it because

paper sluice
#

@modern fiber are you using discord.py?
because client.slash_command doesn't exist in dpy

modern fiber
modern fiber
#

because of slash commands

slate swan
#

Lol

#

...

cold sonnet
#

I'm out

modern fiber
#

.

slate swan
#

can i come with ya pepeShy meh

modern fiber
#

bruh what did I said

slate swan
#

I'm also out

modern fiber
#

..

modern fiber
#

i said im using discord and not disnake

paper sluice
modern fiber
#

OHHHHHHHHHHHH

slate swan
modern fiber
slate swan
#

.py is just the extension means ur using python

slate swan
#

Python already know it's py file

#

sparky too smart

#

so u import like that

paper sluice
slate swan
cold sonnet
#

what

slate swan
modern fiber
#

oh my godness my brain

#

what do I do now BigBrain

slate swan
#

Sleep

paper sluice
cold sonnet
#

it's not pycord he's getting Bot from discord.ext.commands

slate swan
#

When I dont find anything and can't think I just leave coding for few hours

#

then code with my fresh mind and its easy

modern fiber
#

can someone just help me with this part?

cold sonnet
#

did you change this to def __init__()

paper sluice
#

i just open the ide and watch vids

modern fiber
#

pretty sure other shit works.....................

slate swan
modern fiber
dusky pine
#

stop swearing 😠 you can go to jail 😠👎 ||/j||

cold sonnet
#

no the def part...

slate swan
#

...

cold sonnet
#
        super().init(command_prefix=commands.when_mentioned_or("!"))```
slate swan
#

Wrong emoji

#

nice python skills

cold sonnet
#

shut

slate swan
#

🤦‍♂️

#

This one perfect

cold sonnet
#

you shut as well

cold sonnet
#

in your subclass

#

line 17

modern fiber
#

LOL

cold sonnet
#

get redirected

slate swan
# modern fiber where even is that

In python we have __init__ that is used inside class whenever u call a class this method is called u can pass some parameters in it and do like
Class(param1)

slate swan
#

imagine naming it init

modern fiber
#

Like this?

cold sonnet
#

no

slate swan
paper sluice
dusky pine
#

krazy init method (real)

modern fiber
paper sluice
#

super().function calls the function from the parent class

cold sonnet
#
class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or("!"))
slate swan
#

The def part

cold sonnet
#

pp

slate swan
#

your

#

Code

#

**__ __ **

modern fiber
#

What now..

slate swan
#

Remove all code between Bot()

#

when u define it

#

client = Bot()

cold sonnet
#

line 28

slate swan
#

Ur init takes no parame

slate swan
cold sonnet
#

put intents in super().__init__()

modern fiber
#

Like this?

cold sonnet
#

yes

slate swan
#

Ur on_ready is not fine

#

sparky

#

yeah

cold sonnet
#

one step a time

slate swan
#

one at a time

#

alright

cold sonnet
#

just faster

dusky pine
cold sonnet
#

quicker faster more rapid

slate swan
#

im waiting to comment on the client variable name

modern fiber
#

What else do I do

minor totem
#

Long time no see, friends. I haven't checked this channel in a while

slate swan
cold sonnet
modern fiber
slate swan
#

Imagine

#

BRO LEARN PYTHON ENOUGH

modern fiber
#

im going to cry for half an hour then come back and seek help

slate swan
#

chill sparky

vocal snow
#

Wew.chill

cold sonnet
#

oh wait that's not the problem

vocal plover
#

420 - Enhance your calm

cold sonnet
#

missing intents in super().init()

slate swan
dusky pine
#

Sparky can you study for your exams

slate swan
minor totem
# modern fiber Huh?

When you call super().__init__() that's the same as when you do Bot() to discord.py. You still need to pass all arguments. In this case, you need to pass intents. That's what the error tells you is wrong.

slate swan
#

U guys help him

dusky pine
#

close Discord and calm down

cold sonnet
#

he'll be back later

minor totem
#

May I ask, what's the purpose of subclassing the bot here @modern fiber?

slate swan
# modern fiber Huh?

the on_ready method would still be inside the Bot class.

they are asking you to use all the kwargs in super().Init instead of passing it inside your Bot subclass.

if you still want to provide them into the Bot class with py bot = Bot(command_prefix=...) just remove the __init__ or change it to ```py
def init(self, **kwargs):
super().init(**kwargs)

#

yes

#

why even subclass at that moment

vocal snow
#

Funsies

slate swan
#

more like why subclass for no reason

cold sonnet
#

maybe the events will go into the subclass later

#

even though subclassing Bot in discord.py is generally useless

slate swan
#

yeah , cuz they dont implement slots

#

so you can do anything without subclassing

cold sonnet
#

I don't even know what slots are

#

maybe I'd learn it if they did implement it

vocal snow
dusky pine
#

maybe later they'll add custom properties like db conns 🤷

slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 10, in <module>
003 | AttributeError: 'WithSlots' object has no attribute 'apple'
cold sonnet
#

why that

slate swan
#

slots make initialising of classes faster

vocal snow
#

:•|

slate swan
#

you can add external attrs to a class without slots, but not one with slots

cold sonnet
#

o

slate swan
#

use pillow

#

!d PIL.ImageOps.grayscale

unkempt canyonBOT
slate swan
#

for that pride filter you can add a translucent overlay on the base image

minor totem
#

This is not the channel to ask for about PIL. Even though you're adding it to your Discord bot, it has not much to do with your actual Discord bot. Ask in #media-processing or open a help channel.

stiff fern
#
import discord

from discord.ext import commands

class aclient(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='.', 
            intents=discord.Intents.all(),
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name="Testing Functionality"))
        
    async def setup_hook(self):

        await client.tree.sync()

        self.initial_extensions = [
            'cogs.core',

            'cogs.suggestion',
            'cogs.invite',
            'cogs.group',
            'cogs.ping',]

        for ext in self.initial_extensions:
            await self.load_extension(ext)
            print(f'{ext} loaded')

        print(f'\n{self.user} has initialized.')


client = aclient()
#bot.run(os.environ["DISCORD_TOKEN"])

Im having a lot of trouble trying to get my slash commands to work 🥲 they don't show up in the list of available commands so I assume they aren't syncing properly or something because I invited it with the slash command intent and whatever else but client.tree.sync() should work right?

#

Im using @app_command.command() to make them, it worked before so I dont know why it stopped all of a sudden

minor totem
placid skiff
#

reactions intents are enabled in defaults, right?

stiff fern
minor totem
robust fulcrum
#

Guys why my bot is sending this
<bound method perspective.toxicity of <functions.perspective object at 0x7f4bef9c1820>>
It should send a number insted
Help me if possible (tell me if code is needed)

stiff fern
#

So kinda sorta, I tried putting it in the for loop but that didnt really work either