#discord-bots

1 messages · Page 219 of 1

blissful badge
#

Still line 85

smoky sinew
#

you have two on_messages

#

they are conflicting

blissful badge
#

Oh I can only have one on_message for my entire bot?

#

Or is this the issue cogs would solve?

smoky sinew
#

@bot.listen() instead of @bot.event

blissful badge
#

ahhhhh

#

Ok let me verify the functionality with that but I think it would be best for me to just move everything into cogs as we discussed

smoky sinew
#

ok

blissful badge
#

I just don't get it

naive briar
#

!d discord.Client.user

unkempt canyonBOT
smoky sinew
blissful badge
#

Weird, I swore I had tried that and it gave me a different error yesterday, but it wasn't using "listen" so lets seeeee

#

Success!

#

Now to move everything to cogs 🙂

slate swan
#

umm can anyone tell is it important to learn python first to learn discord.py??

slate swan
#

no thats like you would ask can i drive a car without getting a drivers licence

slate swan
#

ok so how am i supposed to learn python from tuts on youtube

#

??

#

yes you can try but you gonna be on this channel every day asking for basic stuff this will annoy you and helpers

unkempt canyonBOT
#
Resources

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

hasty bison
#

how do i send message in another channel

slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
hasty bison
#
@client.command()
async def send_message(ctx, channel_id: int, message: str):
    if ctx.author.permissions.manage_messages:
        channel = client.get_channel(channel_id)
        if channel is None:
            await ctx.send(f"Channel with ID {channel_id} not found.")
            return
        await channel.send(message)
        await ctx.send(f"Message sent to {channel.name}")```
hasty bison
slate swan
#

await message? what do you mean by that

hasty bison
hasty bison
#

thats annother thing that i get an error on

slate swan
#

show error then

hasty bison
#

no attribute to permissions

slate swan
#

cause Member object has no attrbute permissions

#

you prolly want this

#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
hasty bison
#

thanks

hasty bison
#
@client.command()
async def clear(ctx, amount=5):
    """
    Clears a specified amount of messages in the current channel.
    The default amount is 5.
    """
    await ctx.channel.purge(limit=amount+1)
    if amount > 10:
        await ctx.send(f"All messages __cleared__ by {ctx.author.mention}, **_(Message will auto delete)_**")
        time.sleep(6)
        await ctx.channel.purge(limit=1)
    elif amount <= 10:
        await ctx.send(f"{amount} messages __cleared__ by {ctx.author.mention} **_(Message will auto delete)_**")
        time.sleep(6)
        await ctx.channel.purge(limit=1)```
#

i want when it purges messages to send a message in another logs channel

fading marlin
#

time.sleep is blocking. Use asyncio

slate swan
#

!d asyncio.sleep ^

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
hasty bison
#

How can i do like:
if they dont have permissions then print you dont have required perms?

#
@client.command()
@has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount+1)
    if amount > 10:
        await ctx.send(f"All messages __cleared__ by {ctx.author.mention}, **_(Message will auto delete)_**")
        await asyncio.sleep(6)
        await ctx.channel.purge(limit=1)
    elif amount <= 10:
        await ctx.send(f"{amount} messages __cleared__ by {ctx.author.mention} **_(Message will auto delete)_**")
        await asyncio.sleep(6)
        await ctx.channel.purge(limit=1)
blazing flint
#
@client.event
async def on_member_join(member):
  guild = member.guild
  membercount = discord.utils.get(guild.categories, name='Member Count')
  if membercount:
    botcount = sum(m.bot for m in guild.members)
    total_members = discord.utils.get(guild.channels, name=lambda n: n.startswith("🔢"), category=membercount)
    await total_members.edit(name=f'🔢┃Total Members: {guild.member_count}')``` results in an error saying nonetype has no attribute edit
slate swan
blazing flint
#

I know for a fact that it exists though

slate swan
#

try getting it via id then

blazing flint
#
import discord
from discord.ext import commands
from discord import app_commands

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

  @app_commands.command(name="displaymembers", description="Create a new category to display member count.")
  async def displaymembers(self, interaction: discord.Interaction):
    guild = interaction.guild
    if interaction.user.guild_permissions.administrator:
      await interaction.response.send_message("Attempting to create member count category...", ephemeral=True)
      botcount = sum(member.bot for member in guild.members)
      category = await guild.create_category("Member Count", position = 0)
      await guild.create_voice_channel(f'🔢┃Total Members: {guild.member_count}', category=category, user_limit=0)
      await guild.create_voice_channel(f'🤖┃Bot Users: {botcount}', category = category, user_limit=0)
      await guild.create_voice_channel(f'😀┃Humans: {guild.member_count - botcount}', category=category, user_limit=0)
      await interaction.followup.send("Member count channels created successfully.", ephemeral=True)
      await category.edit(position = 0)

async def setup(client):
  await client.add_cog(Displaymembers(client))
``` command cog that makes the chnanel
#

I don't know the id

#

my bot is in multiple servers

dense jackal
#

Hi! Basically my welxome message is sending really late. Its sending like 10 secs after someone join and im wondering why

blazing flint
#

send your code

dense jackal
#

Will do 5 mins plz

blazing flint
#

only the on_member_join function

dense jackal
blazing flint
#

the problem seems to be more dependent on the server you are running it on

smoky sinew
dense jackal
blazing flint
#

@smoky sinew can you help me with my problem

blazing flint
dense jackal
#

What’s wrong with my server

blazing flint
#

like running on a higher capacity computer

#

not a discord server

dense jackal
#

My pc is perfectly fine dude

blazing flint
#

ok then I guess you don't have a problem?

#

what are you using to code your bot

dense jackal
smoky sinew
blazing flint
#

well it could be the problem in some situations

dense jackal
blazing flint
#

I mean... you can try hosting on replit or something

dense jackal
#

My pc stays open 24/7 theres no servers

smoky sinew
#

you are just using a weird library i guess, i have had no problem with regular PIL

blazing flint
#

they have pretty good servers

smoky sinew
#

no they don't

#

replit isn't even made for running a discord bot it gives you a web server to work with

blazing flint
#

I use it to host my bots 24/7

smoky sinew
#

lol

blazing flint
#

and it is in five servers

smoky sinew
#

they give you 512 mb of ram to work with

blazing flint
#

free version is 1 gig of ram

smoky sinew
#

no

blazing flint
#

hacker repl is 2

smoky sinew
#

no

blazing flint
#

boosted repl is 4

smoky sinew
#

stop recommending replit

blazing flint
#

mk

#

can u help me with my problem btw

smoky sinew
#

i don't know what it is

blazing flint
#

scroll up

blazing flint
#

well no that is the command cog

#

go up a bit more

dense jackal
#

Any free servers I can use? Or is it all paid stuff

smoky sinew
#

discord.utils.get does not use a lambda for filtering

blazing flint
#

oh

smoky sinew
dense jackal
smoky sinew
#

!d discord.utils.find @blazing flint

unkempt canyonBOT
#

discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.

Changed in version 2.0: Both parameters are now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
dense jackal
blazing flint
#

you can remove the image if you want it to be fast

dense jackal
#

Why tf would I do that

smoky sinew
dense jackal
smoky sinew
#

it's better than replit

dense jackal
#

Lolll

buoyant quartz
#

why is this not playing the sound i need it to do... Its always saying it isnt connected despite being in a vc with me atm:

user=interaction.user
        voice_channel=user.voice.channel
        # only play music if user is in a voice channel
        if voice_channel is None:
            await interaction.response.send_message('User is not in a channel.')
            return

        guild = interaction.guild
        voice_client: nextcord.VoiceClient = nextcord.utils.get(bot.voice_clients, guild=guild)
        print(voice_client)
        # check if bot is connected to a voice channel
        if voice_client is None or not voice_client.is_connected():
            await interaction.response.send_message('Bot is not connected to a voice channel.')
            return
        
        # check if bot is in the same voice channel as the user
        if voice_client.channel.id != voice_channel.id:
            await interaction.response.send_message('Bot is not in the same voice channel as the user.')
            return
        
        audio_source = nextcord.FFmpegPCMAudio(f'cottonvoice\{sound}.mp3')
        if not voice_client.is_playing():
            voice_client.play(audio_source, after=None)
        await interaction.response.send_message("Done!")```
#

when printing the voice_client it always prints none

slate swan
#

how did i miss this information

#

should i go back to dpy

vale wing
slate swan
#

disnake

#

and the dark side, javascript

smoky sinew
#

why would you

#

if it works don't fix it

vale wing
slate swan
#

im just

#

not satisfied anymore

vale wing
#

As for javascript it's up to you

vale wing
slate swan
#

disnake

vale wing
#

More specifically?

sturdy dawn
#

Hi, I need a great videos resources to learn python.

smoky sinew
cinder tulip
#
@client.tree.command(name="help", description="A list that contains the bot's commands")
@app_commands.choices(helptype=[
    Choice(name='general', value=1),
    Choice(name='admin', value=2)
])
async def help(interaction: discord.Interaction, helptype: Choice[int]):
    if helptype == 1:
        
        embed = discord.Embed(title="General Commands", colour=discord.Color.blue())
        embed.add_field(name="App (slash) Commands", value="-", inline=True)
        embed.add_field(name="Commands", value="-")

        await interaction.response.send_message(embed=embed)

    if helptype == 2:

        embed = discord.Embed(title="Admin-Owner Commands", colour=discord.Color.blue())
        embed.add_field(name="Admin", value="-")
        embed.add_field(name="Owner",value="-")

        await interaction.response.send_message(embed=embed)

what have i wrote wrong for my bot to hit me with the "Application did not respond"

smoky sinew
#

why don't you just use literal?

async def help(
    interaction: discord.Interaction,
    help_type: Literal["General", "Admin"]
) -> None:
cinder tulip
#

Cause Choice seems easier 😭

smoky sinew
cinder tulip
#

Dang it

#

so i have it to rewrite it again

smoky sinew
#

it's not rewriting you're just changing one line of code

cinder tulip
#

yeah i just realized lmao

cinder tulip
hidden torrent
#

hey guys

#

AttributeError: module 'discord' has no attribute 'ext'

#

anyone has this?

smoky sinew
hidden torrent
#

no, got it now too

smoky sinew
hidden torrent
slate swan
#

using cogs why doesn't it reply back to my messages?

smoky sinew
#

?

slate swan
#
class Messages(commands.Cog):
  def __init__(self, bot):
    super().__init__()
    self.bot = bot
    self.chat_log = []
  
  @commands.Cog.listener()
  async def on_message(self, message):
    if message.author == self.bot:
      pass
    elif message.content.startswith("$"):
      pass
    else:
      if isinstance(message.channel, discord.DMChannel):
        .......
        await message.channel.send(...)
#

@smoky sinew

smoky sinew
#

do you have the message content intent?

smoky sinew
smoky sinew
#

hmm

#

btw that == self.bot will never run

#

since bot is an instance of commands.Bot instead of User

#
@commands.Cog.listener()
async def on_message(self, message):
    if message.author == self.bot.user:
        return
    
    if message.content.startswith("$"):
        return
    
    if isinstance(message.channel, discord.DMChannel):
        await message.channel.send(...)
#

you could use an early return here

#

check to see if on_message is running at all

slate swan
#

ahh hollup let me try

slate swan
smoky sinew
#

is on_message running though

slate swan
#

how do I check should I print the message it receives?

smoky sinew
#

sure

slate swan
smoky sinew
#

is your cog loaded?

slate swan
# smoky sinew is your cog loaded?

in messages.py (cog)

def setup(bot):
  bot.add_cog(Messages(bot))

in main.py

bot = commands.Bot(command_prefix="$", intents=discord.Intents.all(), owner_id=1046920598359638036)
 
async def load_extensions():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            try:
                await bot.load_extension(f'cogs.{filename[:-3]}')
                print(f'{filename[:-3]} extension loaded successfully')
            except Exception as e:
                print(f'Failed to load {filename[:-3]} extension. ({e})')

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Streaming(
    name="$help", url='https://www.twitch.tv/xxxxxxxx'))

    print(f"{bot.user} is online with the ID {bot.user.id}")


async def main():
    await load_extensions()

bot.run(TOKEN)
smoky sinew
#

setup should be a coroutine

#

so is bot.add_cog

#

also where are you calling main

slate swan
smoky sinew
#

yes

slate swan
slate swan
smoky sinew
#

just load your extensions in setup_hook

slate swan
#

oh right yeah

slate swan
smoky sinew
#

it's just an event

slate swan
smoky sinew
#

no login

#

and you don't call it, it's an event

slate swan
smoky sinew
#

what

#
@bot.event
async def setup_hook():
    await load_extensions()
#

remove the main function

patent wagon
#

def check(msg):
return msg.content in ['1','2','3'] and msg.author.id==onMove

dont mind anyhignt else but the list. that list is in a loop that runs 3 times and the counter variable is names i. how do i make it so that list generates
['1','2','3'] when i is 0 ['1','2']when i is 1 and ['1'] when i is 2

rocky trench
patent wagon
#

When I is 0 it prints ['1','2,'3']

#

When i is 1 it prints ['1','2']

#

When i is 2 it prints ['1']

#

I don't want to check each lloop what the i is and then assign some stuff to s

#

I need it in one like o code something like s=[str(j) for j in range(i)]

#

But idk how to do ut

#

That's what I mean @rocky trench

rocky trench
#

@patent wagon nested lists?

#

Items = [['1','2','3'],['1','2'],['1']]

#

Then use the i to iterate over the list

patent wagon
#

I found the better solution

#

Thank you tho

dense jackal
#

I coded so my bot sends a welcome message on joining but that welcome message seems to be sent when someone joins a server my bot is in and not only my server

#

Can someone help?

dense jackal
#

Ohhh kk

#

Mb

vital glacier
#
    
    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        data = await self.bot.db.fetchval('SELECT role FROM reactionroles WHERE message = $1 AND emote = $2', str(payload.message_id), str(payload.emoji))
        if data:
            role = payload.member.guild.get_role(int(data))
            await payload.member.remove_roles(role)

Any reason why this wouldn't work?
The on_raw_reaction_add is basically the same, just adds the role and that works.

smoky sinew
#

why are you storing your message id as a string rooSip

magic minnow
#

why doesn't the bot start?

smoky sinew
thick lintel
#

is there a way to turn a command from a Cog into a slash command?

smoky sinew
thick lintel
#

like take the command from the cog and have that same command has a slash command

#

or is there a way to create slash commands inside of classes?

thick lintel
#

oh I've been creating the slash commands in the bot.py file

dense jackal
slate swan
#

just check if the member joined ur guild id then send it

#

so yes

vital glacier
#

how do i prevent the bot getting a role with on_raw_reaction_add?

#

if a bot reacts

narrow rune
#

if not member.bot

vital glacier
#

With payload?

#

also im using it in a cog

dense jackal
stark sapphire
#

The Discord Component Library could not be downloaded. Please help me ㅜㅜ

magic minnow
dense jackal
smoky sinew
smoky sinew
#

and you don't have anything after if

#

and what is member.guild

dense jackal
#

My server?

smoky sinew
#

yeah

dense jackal
#

Which one

smoky sinew
#

if you are comparing ids

smoky sinew
#

users don't have guilds

dense jackal
#

Kk

smoky sinew
#

you're asking if a variable name is right though

#

you can call it whatever

magic minnow
smoky sinew
magic minnow
#

ohk

smoky sinew
#

it's sketchy

magic minnow
smoky sinew
#

digitalocean

narrow rune
#

Free clouds are good if u don’t wanna pay

#

Oracle do 24gb 4 core one

#

It’s arm though and they sometime shut down ur vps for maintenance

stark sapphire
dense jackal
#

I have a big problem when someone joins with no pfp, the bot doesn’t send welcome message as the member.avatar.url or idk is not seen

smoky sinew
# stark sapphire button
class MyView(discord.ui.View):
    @discord.ui.button(
        custom_id="my_button",
        label="My Button"
    )
    async def my_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.send_message("hello")
#

you only need to import discord for this

stark sapphire
smoky sinew
dense jackal
#

Ty

hushed galleon
stark sapphire
#

fuck

#

okay

old oracle
#

Guys can I get help

blissful badge
narrow rune
#

Do u have two instances running?

blissful badge
#

I do not

sick birch
#

You're 100% sure? Restart your computer if you're not.

blissful badge
#

Just did

#

Opened it fresh, still doing it

sick birch
#

Which command did you run?

blissful badge
#

its any of them

#

it sends them each twice

unkempt canyonBOT
#

moderation.py lines 104 to 117

@commands.Cog.listener()   
async def on_message(self, message):
    for bad_word in bad_words:
        if bad_word in message.content:
            print("Banned words scrubbed from chat.")
            await message.delete()
            await message.channel.send("That terminology is not permitted here.")
            channel = self.bot.get_channel(744246685932191805)
            embed=discord.Embed(title=f"A censored word has been scrubbed.",description=f"{message.author} has used the censored term, {bad_word}, and it has been scrubbed from the server.", color=0x00FFFF)
            embed.timestamp = datetime.datetime.now()
            await channel.send(embed=embed)
            channel = self.bot.get_channel(1086293466054656100)
            await channel.send(f"A censored word has been used by {message.author} and scrubbed from chat.")
    await self.bot.process_commands(message)```
blissful badge
#

wait

sick birch
#

You don't need process_commands if you're using a listener()

blissful badge
#

is it the self.bot.process

sick birch
#

Indeed

blissful badge
#

ahhhhhhhhhhhh

#

just realizing the only ones I tried were moderation on second thought, so that makes sense

#

wait actually no it did it on some mc server commands let me check there too

#

Fixed

sick birch
#

Nice!

blissful badge
#

i appreciate you

sick birch
#

Thanks 😁

dense jackal
#

The user avatar, name etc is not uploading on the image

#

That’s the issue, although, no errors is shown up

sinful thistle
#

guys I just cant get this to work

naive briar
#

Get what

unkempt canyonBOT
sinful thistle
#

this is main code

#
if message.content.startswith('!play'):
                url = message.content.strip()
                url = url[6:]
                channel = message.author.voice.channel
                if url.startswith('http'):
                    id_of_vid = url[32:]
                else:
                    id_of_vid = url[24:]
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                vc_Messi = await channel.connect()
                print(id_of_vid)
                audio_source = FFmpegOpusAudio(f'{id_of_vid}.mp3')
                vc_Messi.play(audio_source)

                await message.channel.send(f"Playing {url}")
naive briar
#

!rule 5

unkempt canyonBOT
#

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

naive briar
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
sinful thistle
#

then how do you make a music bot?

#

it says that the file is obus but I am 100000000% sure it is .mp3

shrewd fjord
silk fulcrum
#

there's literally a spotify integration in discord

#

maybe smth like soundcloud

raw quail
#

hello guys. i have a question. if i use @bot.event command twice on code, it will crash and not working?

naive briar
#

It'll override the previous one

raw quail
#

ohhh thank you so much

vale wing
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

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

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

Example...
raw quail
#

thank you !!

shrewd fjord
shrewd apex
#

dont advertise here against rules

dense flower
#

Hey guys, i'm trying to make a discord bot that lets a user flip a coin. Is there a way to prompt the user with either heads or tails when they go to type in the command coinflip? code below:py @tree.command(name="coinflip", description=f"Flip a coin!", guild=guildId) async def self(interaction: discord.Interaction, choice: ):

#

Left choice blank as I wasn't sure what to fill in 😓

slate swan
dense flower
dense flower
#
@tree.command(name="coinflip",
    description=f"Flip a coin!",
    guild=guildId)
@app_commands.choices(choices=[
    app_commands.Choice(name="Heads", value="Heads"),
    app_commands.Choice(name="Tails", value="Tails"),
    ])
async def self(interaction: discord.Interaction,choice: app_commands.Choice[str]):```
dense flower
slate swan
#

cause you named your parameter choice and said choices=[...] either use choice or choices in both places

dense flower
# slate swan cause you named your parameter `choice` and said `choices=[...]` either use `cho...

Oh? In the link you sent it had it exactly like that 👀 . So i'm presuming this'll work better?py @tree.command(name="coinflip", description=f"Flip a coin!", guild=guildId) @app_commands.choices(choices=[ app_commands.Choice(name="Heads", value="Heads"), app_commands.Choice(name="Tails", value="Tails"), ]) async def self(interaction: discord.Interaction,choice: app_commands.choices[str]): ;P

#

oh nope it didn't 😢

slate swan
#

no not in this place

#

notice how in link i sent you they named parameter choices this matters

dense flower
#

OH yeah sorry I follow now my bad

#

sorry i think i'm a bit tired 💀 thanks for clarifying lemon_sweat

slate swan
#

👍

dense flower
# slate swan 👍

Any chance you also know how to do this for an integer? i'm trying to do a value: int and not allow it to go over 100

#

idk if that's possible but hoping it is 😅

slate swan
#

is this what you want?

#

@dense flower ?

shrewd fjord
#

Um anyone here ? opsi

dense flower
slate swan
dense flower
#

Last question before I head off to bed, i'm trying to design this coinflip thing so that it sends a message with a gif, then waits 5 seconds, deletes the gif and then sends the results. This is what i've got so far:py gif = discord.File('Coinflip.gif') await interaction.response.send_message(f"Thinking...", file = gif, delete_after=5) await interaction.response.send_message(f"{results}")

The only issue is that it's already been responded to so it doesn't seem to like that. I tried interaction.followup but it doesn't look as clean as what i'm going for. I see a lot of bots able to just send another message so i'm wondering how I can achieve that

slate swan
dense flower
slate swan
hushed galleon
slate swan
#

you can use asyncio.sleep to wait 5 seconds

#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
dense flower
dense flower
#

ah edit_message()

slate swan
#

i belive it will be interaction.message.edit() not sure about it tho

#

yep like that ^

shrewd fjord
#

ok lemme drop my ques

dense flower
slate swan
unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

slate swan
#

!d discord.Interaction.message

unkempt canyonBOT
shrewd fjord
#

idk if you guys know we can do some thing like:

btn = discord.ui.Button(...........)
async def callback(inter):
   ...
btn.callback=callback

my question is how do i access the Button object (without da btn var) tho my current code is not the same

dense flower
# unkempt canyon

oh so wouldn't that edit the users message rather than the responses?

tough lance
#

Slash commands aren't used with messages

shrewd fjord
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
slate swan
shrewd fjord
dense flower
dense flower
hushed galleon
shrewd fjord
#

i fixed it by subclassing the button on the view

silk fulcrum
#

xD I think I should make fair be even more rare

hasty bison
#

how do i use discord_slash on pycharm

hushed galleon
#

discord.py 2.0 came out last year too which adds support for message components / slash commands

dense jackal
#

Anyone got a docs for this?

#

Message sent in the channel is took and is added into the bot’s embed added with an autoreactions and autothreads

slate swan
#

So many docs

maiden fable
#

Actually its easier than u might think

fading marlin
dense jackal
maiden fable
#

So u use on_message event to check for messages in the specific channel, use channel.send(embed=...) to send the embed, then use a wait_for to wait for any reactions on the message, and if the reaction happens, then u create a thread using channel.create_thread

dense jackal
maiden fable
#

u can access the message content with message.content and u get the message in the on_message event

#

!d discord.on_message

unkempt canyonBOT
#

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

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

Warning

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

!d discord.Message.content

unkempt canyonBOT
maiden fable
#

the on_message docs are above, message.content is this ^

dense jackal
#

Cant find one

maiden fable
#

AFK Command?

dense jackal
#

Yeah like ?afk test

#

Like dyno’s

#

?afk test

maiden fable
#

So when u set the afk message, and when the person goes offline/afk, it will send that message?

dense jackal
maiden fable
#

For the second part, u use on_message
You maintain a database of users who are AFK and just change the values as to when to send the message and when to not, and for the command, u can do:

async def afk(ctx, *, message: str):
    # message is the message which the bot will send whenever someone mentions the author
dense jackal
#

And this

maiden fable
#

It will, sure

dense jackal
#

Its easier to me lol

maiden fable
#

!d discord.Message.mentions check this list for author mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
smoky sinew
dense jackal
smoky sinew
#

if you want it to persist a list won't work

blazing flint
formal basin
#

How do I do an event that times out someone

blazing flint
#

You mean a command?

smoky sinew
unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
formal basin
formal basin
blazing flint
slate swan
#
import datetime
duration = datetime.timedelta(minutes=5)
await member.timeout(duration)```
smoky sinew
#

put imports at the top though

formal basin
#

Yeah I know

smoky sinew
formal basin
#

global author_msg_counts

    author_id = ctx.author.id
    # Get current epoch time in milliseconds
    curr_time = datetime.datetime.now().timestamp() * 1000

    # Make empty list for author id, if it does not exist
    if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    # Append the time of this message to the users list of message times
    author_msg_times[author_id].append(curr_time)

    # Find the beginning of our time window.
    expr_time = curr_time - time_window_milliseconds

    # Find message times which occurred before the start of our window
    expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    # Remove all the expired messages times from our list
    for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    # ^ note: we probably need to use a mutex here. Multiple threads
    # might be trying to update this at the same time. Not sure though.

    if len(author_msg_times[author_id]) > max_msg_per_window:
     duration = datetime.timedelta(minutes=15)
     await ctx.send("Stop Spamming")
     await author.timeout(duration)

formal basin
smoky sinew
#

what is ctx? you said this was an event?

formal basin
#

Wait never mind I got it

slate swan
blazing flint
blazing flint
#

Nvm

slate swan
#

guys help.
Возникло исключение: PrivilegedIntentsRequired
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
discord.gateway.WebSocketClosure: '
During handling of the above exception, another exception occurred:
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 4014
During handling of the above exception, another exception occurred:
File "E:\My Code\tic tock.py", line 14, in <module>
client.run('token my bot)
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

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

smoky sinew
#

It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

slate swan
#

Ok

tall pond
#

How do I code a discord bot on my phone

smoky sinew
tall pond
#

I do but not with me I’m not home rn

formal basin
#


@client.listen("on_message")
async def coolmessage(message):
    if message.author.id == client.user.id:
        return
    message.content

    blockedwords = [
        'idiot', 'Idiot', 'IDIOT', 'IDiot',  'dum', 'Dum', 'DUM' ,'DUm', 'DuM', ' stupid', 'STUPID',
        'Stupid', 'STupid'
    ]

    if any(word in message.content for word in blockedwords):
        await message.delete()
        await message.channel.send(
            f"Please don't say that {message.author.mention} ", delete_after=5)


    normalmsg = ['hi', 'Hi', 'Hello', 'hello']

    if any(word in message.content for word in normalmsg):
       await message.channel.send(f"Hi {message.author.mention}")


    global author_msg_counts

    author_id = message.author.id
    # Get current epoch time in milliseconds
    curr_time = datetime.datetime.now().timestamp() * 1000

    # Make empty list for author id, if it does not exist
    if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

    # Append the time of this message to the users list of message times
    author_msg_times[author_id].append(curr_time)

    # Find the beginning of our time window.
    expr_time = curr_time - time_window_milliseconds

    # Find message times which occurred before the start of our window
    expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]

    # Remove all the expired messages times from our list
    for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    # ^ note: we probably need to use a mutex here. Multiple threads
    # might be trying to update this at the same time. Not sure though.

    if len(author_msg_times[author_id]) > max_msg_per_window:
     duration = datetime.timedelta(minutes=15)
     await message.channel.send(f"No Spamming. {message.author.mention} has been timed out for 15 minutes for spamming")
     await author.timeout(duration)

formal basin
tall pond
#

How do I code a discord bot on my phone

tall pond
formal basin
tall pond
#

Yes

smoky sinew
#

!resources

unkempt canyonBOT
#
Resources

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

smoky sinew
#

sort by beginner

tall pond
#

Ok

tall pond
formal basin
#

Please

tall pond
#

What do I choose for the type

smoky sinew
#

whatever you want

tall pond
smoky sinew
#

sure

#

what phone

tall pond
#

So it works

#

iPhone 13

smoky sinew
#

maybe

formal basin
smoky sinew
#

!d discord.Message.author

unkempt canyonBOT
formal basin
smoky sinew
#

because you didn't define it? what do you mean'

formal basin
#

Ok

formal basin
smoky sinew
#

just use message.author instead

formal basin
formal basin
#

Oh

formal basin
#

?

smoky sinew
#

huh?

formal basin
smoky sinew
#

no

#

are you using replit???

formal basin
#

Yes

smoky sinew
#

change it in pyproject.toml

#

remove your old line and put

#

discord-py = "^2.2.2"

formal basin
#

Ok

tall pond
#

Anyone have a code that I can use for a discord bot on replit idk how to make one

formal basin
stone palm
#

how do i define MyContext for a custom context?

slate swan
#

subclass commands.Context class

fading marlin
#

^ then override Bot.get_context

stone palm
#

can this be done in a cog

stone palm
stone palm
#

yeah referring from there

#

i have a tag class

#

i added MyContext subclass under that

#

is that right

#

since i need the function within that class

vital glacier
#

How do i remove the [' '] from inside of the embed?

stone palm
#

after whatever your query is

vital glacier
#

how do u mean

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
stone palm
#

right thats better

slate swan
#

use this to join all missing permissions to one string separated by something

slate swan
stone palm
# slate swan show some code
class Tag():
    def __init__(self, name: str, author: int, description: str, created_at: datetime):
        self.name = name
        self.author = author
        self.description = description
        self.created_at = created_at

class MyContext(commands.Context):
    async def get(self, name):
        tag_data = await self.database["tags"].find_one({ "_id" : self.guild.id })
        if tag_data:
            if name in [x["name"] for x in tag_data]:
                author=[x["author"] for x in tag_data if x["name"] == name][0]
                description=[x["description"] for x in tag_data if x["name"] == name][0]
                created_at=[x["created_at"] for x in tag_data if x["name"] == name][0]
                return Tag(name, author, description, created_at)
            else:
                raise commands.BadArgument(f"No tag named {name}")
        else:
            raise commands.BadArgument(f"No tag named {name}")
slate swan
#

okay now you need to tell bot to use this context

smoky sinew
#

!e ```py
permissions = ["ban_members"]
print(", ".join([p.replace("_", " ").title() for p in permissions])

#

!e ```py
permissions = ["ban_members"]
print(", ".join([p.replace("_", " ").title() for p in permissions]))

unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

Ban Members
smoky sinew
#

@vital glacier

vital glacier
#

Ah I see

stone palm
#

is that correct

slate swan
stone palm
#

but then how do I define MyContext

smoky sinew
#
class MyContext(commands.Context):
    pass
smoky sinew
#

sure

slate swan
#

in command

stone palm
slate swan
#

!src

unkempt canyonBOT
slate swan
#

this is a command

stone palm
#

oh

#

no not in that way i meant

#

i meant in class MyBot

slate swan
#

yeah?

stone palm
#

the cls=MyContext is undefined

#

MyContext

slate swan
#

you need to import it

stone palm
#

is undefined

stone palm
slate swan
#

from something import MyContext

slate swan
stone palm
#

right that makes so much sense

#

wait no

#

what

#

undefined name 'MyContext' in main.py

#

am i supposed to import MyContext from a cog to main.py

smoky sinew
#

you don't need to import anything just put MyContext in main.py

stone palm
smoky sinew
#

what is interaction.get

stone palm
#

isnt that how its supposed to work

#

get is a function in MyContext

slate swan
#

yes but Intraction and Context are two other things

stone palm
#

doesnt it work for both

smoky sinew
#

no

slate swan
#

Interaction is for slash commands while Context is for prefixed commands

smoky sinew
#

interaction is not a type of context

stone palm
#

someone told me it works for both in the discord.py server

smoky sinew
#

if you use hybrid commands it will

stone palm
#

so cant i use interaction at all with a custom context

slate swan
#

maybe they means hybrid command

formal basin
#

Guys what version is discord on

stone palm
#

probably

formal basin
#

When you import discord

smoky sinew
slate swan
stone palm
#

hmmm

slate swan
#

how i can make a echo command ?

#

That is, the user wrote something and he repeated it

gilded cedar
#

Did replit had enough of keep_alive or is it just me?

slate swan
slate swan
slate swan
# slate swan thx

it would roughly look like this:

async def echo(ctx, *, message):
    await ctx.send(message)```
slate swan
#

if i want to use slash commands but using cogs how do I do it? (mention me)

smoky sinew
unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
slate swan
smoky sinew
#

sure

vital glacier
#
async def prefix(bot, message):
    data = await bot.db.fetchval('SELECT prefix FROM prefix WHERE guild_id = $1', message.guild.id)
    if data:
        return commands.when_mentioned_or(data[0])(bot, message)
    else:
        return commands.when_mentioned_or(',')(bot, message)

Currently I have this and I'm trying to make it so it can also respond to a custom set prefix for the user only, so u would have the guild prefix, a 'self' prefix (which only the author can use if setup), and then the mention.

The guildprefix and mention prefix already work
Just need to add the selfprefix but no idea how to make that work.

#

and also make it work so it respond to the all 3 if they are issued

fading marlin
#

"context menus cannot be defined inside a class"

thin raft
#

reading was never an option

slate swan
#
@app_commands.command(description='Kicks a member')
@app_commands.describe(member='member to kick')
@app_commands.default_permissions(ban_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason:str):
    embed = Embed(color=0x003fff)
    embed.set_author(name=f"{member} was kicked | {reason}", icon_url="https://cdn-icons-png.flaticon.com/512/6364/6364343.png")
    await interaction.response.send_message(embed=embed)
    await member.kick(reason=reason)

slash command not showing

smoky sinew
#

did you sync it?

slate swan
# smoky sinew did you sync it?
@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Streaming(
    name="/help", url=url))
    print(f"{bot.user} is online with the ID {bot.user.id}")

    await bot.tree.sync()
smoky sinew
#

make a message command to sync it

slate swan
smoky sinew
#
@bot.command(name="sync")
async def sync_globally(ctx: commands.Context) -> None:
    await bot.tree.sync()
    await ctx.send("Synced the bot tree.")
slate swan
slate swan
graceful ermine
#

Hey, I am getting this error how could I fix this?

nextcord.ext.commands.errors.BadArgument: Converting to "File" failed for parameter "file".

#
@bot.command()
async def sendfile(user: nextcord.User, *, file: nextcord.File):
    """Send a file to a user."""
    try:
        with open(file, 'rb') as f:
            file = nextcord.File(f)
            await user.send(file=file)
        await user.send(f"File '{file}' sent to {user.mention}")
    except Exception as e:
        await user.send(f"An error occurred: {e}")```
#

This happened after running the command

tawdry sparrow
#

I am trying to send a message to a specific channel using discord py
However I don't want to start the bot, I just want to send a message.
Sadly the bot is not showing any guilds

async def main():
    config = DiscordConfiguration()
    client = Client()
    await client.login(config.token)
    print(client.guilds) # empty
asyncio.run(main())
sick birch
potent spear
sick birch
#

Well, actually nevermind

tawdry sparrow
sick birch
potent spear
#

I think some sort of webhook is what he needs

sick birch
tawdry sparrow
#

I just want to send a message, the thing shouldn't be interactive

sick birch
#

You'd just send a POST request to the appropriate endpoint using something like requests or aiohttp

tawdry sparrow
#

Thank you I have been banging my head for a while

slate swan
#

hi

#

how can i change these colors

#

@sick birch srry for ping

#

can anyone tell me?

#

i need it to be purple but when i put "PURPLE" it gives me "error traceback"

smoky sinew
slate swan
smoky sinew
#

colorama only supports these iirc

smoky sinew
slate swan
slate swan
smoky sinew
unkempt canyonBOT
#

Hey @regal perch!

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

regal perch
#

Hi Guys, I'm new to bot development with python. I've been creating this bot that has the prefix "-", I'm trying to get the bot to respond "Hello, How Ware you??" when I execute the -greet command. But it only does it when I tag it when doing the command, that is, I say "-greet @bot, so I wanted to know how I can make the bot execute the command without needing to tag it in the message. THANK YOU SO MUCH FOR READING. Below is the code. https://paste.pythondiscord.com/opimezijuq

#

I don't know how to make the code show up here without the link.

smoky sinew
#

code looks fine to me

smoky sinew
#

the second one

#

put process_commands at the end

regal perch
smoky sinew
#
@bot.event
async def on_message(message):
    if message.author.bot:
        return
    
    if bot.user.mentioned_in(message):
        await message.channel.send(...)

    await bot.process_commands(message)
regal perch
#

Thanks

#

I'll try the code, now I'll come back

#

Still the same, it works only when I tag the bot in the message @smoky sinew

smoky sinew
#

you need the message content intent

#
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
    intents=intents,
    command_prefix="-"
)
#

and make sure to enable it in your developer portal as well

regal perch
smoky sinew
#

yes

regal perch
honest rover
#

Hey I havent used discord.py in a while and it seems that my cog commands are not being loaded.

This is how I am loading the cog files

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

Cog looks like this

import discord
from discord.ext import commands

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

    @commands.command()
    async def command(self, ctx):
      . . .

def setup(bot):
    bot.add_cog(Help(bot))

But whenever I call that command it comes up as discord.ext.commands.errors.CommandNotFound

#

Anything i might have missed since last updates? Intents are enabled

intents = discord.Intents.all()
bot = commands.Bot(command_prefix = 's.', case_insensitive = True, intents = intents)
honest rover
#

long time no see

smoky sinew
#

bot.load_extension is a coroutine now, so is setup and add_cog

#

you should do extension loading in Bot.setup_hook

honest rover
#

I see, its been a while

#

Let me check that, thanks

shrewd fjord
#

As because i think if you tak the bot, still it needs intent

#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
smoky sinew
#

the issue is the bot can't see message content unless it's pinged

shrewd fjord
#

How it can see mentions then pithink

#

Maybe message.mentions still works ig or no?

#

Idk maybe i am just not understanding the context, my bad

smoky sinew
shrewd fjord
smoky sinew
#

yes it does?

shrewd fjord
#

Ohk, cool then 💀

#

It gets only mention or just the whole content in it?

smoky sinew
#

the whole content

shrewd fjord
#

Demnn, its like bypassing message_content intent kek

smoky sinew
#

yeah.. that's the point

#

because the bot needs to know the message it's mentioned in

shrewd fjord
#

Discord should remove that i think

smoky sinew
#

no why would they

shrewd fjord
#

I mean bot should not know the content when the intent is not enabled

smoky sinew
#

what

shrewd fjord
#

I am tripping hard 😂

smoky sinew
#

understood

#

have a great day

shrewd fjord
slate swan
smoky sinew
#

? scraped?

blazing flint
#

https://paste.pythondiscord.com/maqasaqoto

the print statement in the section where I am trying to define the user allowed to use my select menu is never made so I am wondering what I am doing wrong to set each item in the select menu only available to current_player

slate swan
#

question...

so i'ved tried this a few different ways... but i'm stumped...

so i have a random vc generator. when members leave it, the channel deletes, but if a user jumps from that channel to another, it doesn't delete until both temp channels == 0 users... thoughts?
i'm only seeing before.channel initiated when they leave both/all channels.

if (
            before.channel is not None
            and before.channel.name in self.channel_items 
            and len(before.channel.members) == 0
            ):
            await self.channel_generator_deleter(before=before, after=after, member=member)
if (
            before.channel is not None 
            and before.channel.id in self.channel_items 
            ):
            print("before channel is not none and before channel id in channel info")
            print("Before sleep: ", len(before.channel.members))
            await asyncio.sleep(1)
            print("After sleep: 1", len(before.channel.members))
            if len(before.channel.members) == 0:
                await self.channel_generator_deleter(before=before, after=after, member=member)
shrewd fjord
shrewd fjord
#

As because before, after is already a channel object lol

shrewd fjord
#

And are you doing it inside "event"?

slate swan
shrewd fjord
#

what event u r using? voice_state_update?

slate swan
shrewd fjord
slate swan
shrewd fjord
#

i think then it will be

after.channel.members

#

like u were doing

#

after.channel.members

#

my bad lol i thought "before, after" is channel objects

slate swan
#

maybe it's the way the channel_info is being accessed...

shrewd fjord
slate swan
#

right

shrewd fjord
shrewd fjord
# slate swan right
        if before.channel is not None and before.channel.id in self.channel_info:
            await asyncio.sleep(1)
            if len(before.channel.members) == 0:
                await self.channel_generator_deleter(before=before, after=after, member=member)
#

no need of this imo

#
       if after.channel is not None and after.channel.id in self.channel_info:
            await asyncio.sleep(1)
            if len(after.members) == 0:
                await self.channel_generator_deleter(before=before, after=after, member=member)
        if after.channel is not None and after.channel.id in self.channel_info:
            await asyncio.sleep(1)
            if len(after.channel.members) == 0:
                await self.channel_generator_deleter(before=before, after=after, member=member)
#

this is ok

#

but why u r using the same if statement two times?

slate swan
#

no i must of pasted that line twice :c

shrewd fjord
#

no need of this first if statement

shrewd fjord
slate swan
#

so i'm guessing...


        if (
            after.channel is not None 
            and after.channel.id in [
                                    channel["voice_id"] for channel in self.channel_info.values()
                                    ]
            and len(after.channel.members) == 0
        ):
            await self.channel_generator_deleter(before=before, after=after, member=member)

        if (
            after.channel is not None 
            and after.channel.id in self.channel_info
            and len(after.channel.members) == 0
        ):
            await self.channel_generator_deleter(before=before, after=after, member=member)
#

one of these...

shrewd fjord
#

yeah one of this

#

but the first if statement is bt different?

#

what does self.channel_info look like?

#

self.channel_info = channel_info
chnnel_info isnt defined?

#

i think u r trying to make it a dictionary?

#

self.channel_info={}

slate swan
#

channel_info = {
    "ChannelGenerator":"",
        "best_textstat": "",
        "voice_id": "",
        "text_id": "",
}
shrewd fjord
#

then 1st if statement is right

#

not the 2nd one

formal basin
#

What does this error mean

slate swan
#

show full code

formal basin
slate swan
#

what when the if is false the varriable muted_role wont exist

formal basin
naive briar
#

Define it correctly

#

!e

if False: # condition
    cat = "meow"

print(cat)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     print(cat)
004 |           ^^^
005 | NameError: name 'cat' is not defined
shrewd fjord
unkempt canyonBOT
#
Scoping rules

A scope defines the visibility of a name within a block, where a block is a piece of python code executed as a unit. For simplicity, this would be a module, a function body, and a class definition. A name refers to text bound to an object.

For more information about names, see /tag names

A module is the source code file itself, and encompasses all blocks defined within it. Therefore if a variable is defined at the module level (top-level code block), it is a global variable and can be accessed anywhere in the module as long as the block in which it's referenced is executed after it was defined.

Alternatively if a variable is defined within a function block for example, it is a local variable. It is not accessible at the module level, as that would be outside its scope. This is the purpose of the return statement, as it hands an object back to the scope of its caller. Conversely if a function was defined inside the previously mentioned block, it would have access to that variable, because it is within the first function's scope.

>>> def outer():
...     foo = 'bar'     # local variable to outer
...     def inner():
...         print(foo)  # has access to foo from scope of outer
...     return inner    # brings inner to scope of caller
...
>>> inner = outer()  # get inner function
>>> inner()  # prints variable foo without issue
bar

Official Documentation
1. Program structure, name binding and resolution
2. global statement
3. nonlocal statement

naive briar
#

The condition wasn't true, the variable will not exist

shrewd fjord
#

add:
else:
muted_role="something"

formal basin
#

Like that

slate swan
# shrewd fjord not the 2nd one

figured it out! ty for the insight!


        if (
            after.channel is not None 
            and after.channel.id in [
                                    channel_data["voice_id"] for channel_data in self.channel_info.values() if isinstance(channel_data, dict)
                                    ]
                and len(after.channel.members) == 0
                ):
                    await self.channel_generator_deleter(before=before, after=after, member=member)
formal basin
slate swan
#

indent it correctly

#

also you need to add something to if

shrewd fjord
slate swan
#

or if you only want to handle else revert the if to be negation

formal basin
shrewd fjord
#

etc

formal basin
#

Also I did intend it properly but it still says wrong

shrewd fjord
slate swan
shrewd fjord
#

again raising the error

shrewd fjord
formal basin
#

Wait you know the asyncio sleep

#

Is it in seconds?

slate swan
#

Yes

formal basin
#

Thanks

shrewd fjord
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
zealous dagger
#

Hey how to make a message disappear itself

#

@commands.is_owner()
@bot.command()
async def purge(ctx,amount:int):
    await ctx.channel.purge(limit=amount)
    await ctx.send("Purged",ephemeral=True)
#

Recently I got to know that ephemeral doesn't work for prefix commands

#

So what I want is that the message which I sending in the last to disappear itself.

#

@upbeat otter

naive briar
#

What does disappear itself suppose to mean

zealous dagger
#

I mean that

#

when I use

#

mb!purge 5 The message that is sent in the last like Purged

#

should disappear after a limited period of time

#

@naive briar

will this work if I store the last message in a var and then use msg.delete()

vocal snow
#

!d discord.abc.Messageable.send

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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
vocal snow
zealous dagger
#

You are a genius

#

by the way

#

if I want to look some stuff how can I use this comamnd

#

!d discord.abc.Messageable.send

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.11)") 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.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
mighty sun
#

Hello, when I create a @bot.command it works perfectly, but as soon as I create a @bot.event underneath it, it removes my commands from the bot command, do you know why? Thanks in advance

slate swan
mighty sun
# slate swan what event is that? show full code

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

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

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

@bot.event
async def on_ready():
print ("le bot impact es chaud à faire feu !")

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

@bot.command()
async def re(ctx):
await ctx.send("nard !")

@bot.command()
async def fruitix(ctx):
await ctx.send("Fruitix es le plus beau des dieux")

@bot.command()
async def quoi(ctx):
await ctx.send("feur")

@bot.command()
async def clear(ctx, amount:int = 5):
await ctx.channel.purge(limit=amount)

@bot.command()
async def creeper(ctx):
await ctx.send("Voici le nombre de spawner a creeper des membres de la faction\n\nFruitix : 15\nTascrulaviecunki : 1\nTartoCerise : 11\nTartoFruit : 17\nSherinoxxx : 92\n")

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick (ctx, member:discord.Member, *, reason=None):
if reason == None:
reason="aucune raison"
await ctx.guild.kick(member)
await ctx.send(f"le joueur {member.mention} a été kick du serveur impact pour {reason}")

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban (ctx, member:discord.Member, *, reason=None):
if reason == None:
reason="aucune raison"
await ctx.guild.ban(member)
await ctx.send(f"le joueur {member.mention} a été banni du serveur impact pour {reason}")

@bot.event
async def on_message(message):
if message.content == "fruitix".lower():
await message.channel.send("Laisse le dieu tranquille !")

slate swan
#

i belive you mean it happens after defining on_message evnet?

#

@mighty sun ^

mighty sun
#

I would like to be able to write a text and that the bot answers me, when I use the command it works, for example ".fruitix" but when I do "fruitix" it doesn't work... and I don't find why... I have already read what you sent me but I don't understand..

#

@slate swan

#

same to make a messafe when people join my server it does not work

#

i add : "await bot.process_commands(message) but It still doesn't work

slate swan
#

unindent await bot.process_commands(message) to be outside if

mighty sun
#

where should I put it?

slate swan
#

unindent

mighty sun
slate swan
#

put cursor at this line and press Shift + TAB

mighty sun
#

here ?

slate swan
#

too much

mighty sun
#

i'm verry sorry..

slate swan
#

await must be on the same vertical line as if

mighty sun
#

it's ok ?

slate swan
mighty sun
#

ok i start for testing

#

and for the welcome message I have to add this command too ?

#

it works thank you very much < 3

now I have to set the other @bot.event...@slate swan

slate swan
#

you should use event on_member_join iirc

#

!D discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

I added a second message command and the second one doesn't work. @slate swan

slate swan
#

you cant define 2 events with the same name

#

you need to implement this code in one method

mighty sun
#

How can I do then for my example?

#

@slate swan

slate swan
#

Add elif below and check for creeper

mighty sun
#

below what? @slate swan

slate swan
#

below if

mighty sun
#

@slate swan

slate swan
#

Do you know how Basic if elif structures looks Like?

mighty sun
#

no sorry I'm a beginner... 😦 I can't find anyone to help me, I'm sick of it. @slate swan

#

you are the only one who has ever helped me...

meager chasm
#

If you want free resources to learn python you can check !resources

mighty sun
#

ah 😦 ok... but for this elif function can you help me please?

unkempt canyonBOT
#
Resources

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

naive briar
#

!d elif

unkempt canyonBOT
#

8.1. The if statement

The if statement is used for conditional execution:


if_stmt ::=  "if" assignment_expression ":" suite
             ("elif" assignment_expression ":" suite)*
             ["else" ":" suite]
``` It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section [Boolean operations](https://docs.python.org/3/reference/expressions.html#booleans) for the definition of true and false); then that suite is executed (and no other part of the [`if`](https://docs.python.org/3/reference/compound_stmts.html#if) statement is executed or evaluated). If all expressions are false, the suite of the [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) clause, if present, is executed.
mighty sun
naive briar
#

No

mighty sun
#

grrr..; ! 😦

naive briar
#

!e

a = False

if a:
    print(0)
elif not a:
    print(1)
else:
    print(2)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
mighty sun
#

i don't understand.. @naive briar

vale wing
#

Because you never learned about conditional operators

#

Sorry to say this, but you need to learn basic python

meager chasm
#

Unfortunately there is no shortcut to learning the basics ^-^

vale wing
#

Youtube videos or online courses are the way to go

mighty sun
#

ok thank you... :/

#

@vale wing@meager chasm

unkempt canyonBOT
#
Resources

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

mighty sun
#

I succeeded 🙂

#

thank you, I have another question, I would like to put an administrator permission on my command ".clear" how can I do?

scarlet aurora
#

how do u do a hybrid command so it is slash and prefix at the same time, or do you just have to just duplicate all commands to have 1 slash, and 1 prefix?

scarlet aurora
#

here have my clear command for reference

#

@sick birch

sick birch
scarlet aurora
#

ok

dull terrace
mighty sun
#

@slate swan thank

gilded cedar
#

do you guys any free uptime monitoring ideas other than UptimeRobot?

maiden fable
#

I don't think so

dull terrace
#

Get the ID of the replied to message then fetch the message

#

Then convert the embed into a dictionary

#

fetched_message.embeds[0].to_dict() IIRC

drifting arrow
#

Is it possible to make a discordbot join a server but as a regular user?

slate swan
#

it cant join on its own but i belive it can create a server

drifting arrow
#

Then how would someone be able to monitor a lot of discord servers using a discordbot without actually having the bot in those servers?

slate swan
#

depends what do you mean by monitor

drifting arrow
#

Just get the basic information on a server like who is in it

slate swan
#

the bot must be in to know that

drifting arrow
#

So they're either using social engineering to invite the bot or doing something against TOS to see inside a discord server?

slate swan
#

if any bot has data from server it is not in then its against Discord ToS for sure

drifting arrow
#

I'm guessing it's against TOS to create an application that logs into a discord account that's in a server just to see what's up? such as to see who is in it and what roles etc?

slate swan
#

yeah

#

any automated stuff that is not done via bot or webhook is against tos

slate swan
#

I got rid of cogs

#

But my app_commands don’t work

#

hey i have just complted learning python now from where can i learn discord.py???

#

@slate swan

#

bruh u online reply wen

#

@slate swansry for another ping

slate swan
#

did you even open it?\

#

why there is no next option??

slate swan
#

then read its content and try do make some basic stuff

slate swan
#

what did you learn in 2 nights

slate swan
slate swan
#

not everything has a cool tutorial with steps to walk you through

#

my 2 nights contain 24 hrs i opened my eyes for 24hrs

slate swan
#

do it on your end

#

heh?

#

and try it out

change something and see what it does thats how you learn

slate swan
#

okay

slate swan
#

How do I make the bot respond to messages?

agile lark
#

Hello I want help?

slate swan
#

instead of .send

agile lark
#

Can anyone tell me what is data base management and why do i need to learn it?

karmic nimbus
#

how do i add add roles to multiple user?

async def addrole(ctx, member: discord.Member):
visual ruin
#

how to i uninstall the discord_slash folder in this location: "/python3.9/site-packages/discord_slash"

slate swan
visual ruin
#

Yea but how to i reinstall it. It has a error in the manage_commands.py

slate swan
#

it should update it to latest version

#

but keep in mind it is very outdated

visual ruin
#

ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash

slate swan
#

yeah you need to rewrite your code to not use discord slash

#

its outdated

visual ruin
#

ok, how to i at options to slash commands?

brisk pagoda
#

Ello, i cant seem to get the reactions from a message

#
        msg = await channel.send(embed=giveaway_embed)
        await msg.add_reaction("🎁")

        await asyncio.sleep(duration_secs)
        reactions = msg.reactions
#

@slate swan cans ya help

#

it keeps returning an empty string even though theres reactions to it

slate swan
visual ruin
#

I use these:

import os
import discord
import discord.ext import commands, tasks
import interactions

slate swan
#

discord and interactions are both discord libraries you cant choose 2 at once you need to choose one to use

visual ruin
#

Which of them has the function to use options in slash commands?

slate swan
#

discord has for sure

#

its most popular

visual ruin
#

I want to use this command for example:

@bot.command(
name="say",
description="Sagt etwas im Namen des Bots.",
options=[Option(name="text", description="Der Text, der gesagt werden soll", type=OptionType.STRING, required=True)]
)
async def say(ctx: SlashContext, text: str):
await ctx.send(text)

slate swan
#

try out some commands from examples and see what you need

formal basin
#

I have this code here to mute someone if there spamming but once someone gets muted it mutes people if they say one word

formal basin
slate swan
#
embed.add_field(name="Платформа", value=f"**Обработано команд:** {commands_count}\n**Задержка:** {delay*1000:.2f} мс\n**Запущена:** {uptime} сек назад", inline=True)```
slate swan
#

why discord removes permissions for particular member in a channel when he lefts and if he rejoin perms are not there :-;

dull terrace
#

is anyone else completely icked out by these people creating full betting apps as discord bots

#

sharpline sports

#

"members made $500, 000" in 2022"

dull terrace
#

unless you're somehow storing everyone under the same dictionary key

#

also storing it in a list like that makes no sense to me

#

wouldn't you just add or minus one and store a timestamp with it to simplify things

dull terrace
#

based on what you've sent, that's the only way i could see it

formal basin
#

I’m not good with storing

#

Could you show me

agile lark
#

Hello i am really sad.Can anyone help please?😢

dull terrace
agile lark
#

Can anyone tell me what basics do i need to learn then go for coding?

dull terrace
#

trying to remember how i did this for one of my apps

formal basin
dull terrace
#

a storing file?

formal basin
#

Like a json file or a txt

dull terrace
formal basin
#

Or a cog

dull terrace
#

json stores dictionaries so yes, so does text files but you should basically never be using text files

formal basin
#

I use json anyway

dull terrace
#

and i would recommend switching to databases and not using json, but if you're new to python and this isn't something you'll release for lots of people i wouldn't worry about it for now

formal basin
#

This is a private bot

#

How are going to put this data into the json file?

dull terrace
#

time stamps are just the number of seconds since a date

#

jan 1st 1970

formal basin
#

Oh

#

Do I need to import anything?

sick birch
#

How long is a while?

slate swan
#

Guys someone has tool?
Exampple:
Using Discord tokens 10limit or more
Using discord channel id(no limit)
Message send: what i want
Au dm response: what i want