#discord-bots

1 messages · Page 1008 of 1

unkempt canyonBOT
echo wasp
#

is that correct?

slate swan
#
@commands.has_permissions(administrator=True)
cloud dawn
#

You guys mean has_guild_permissions

heady sluice
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of
the permissions necessary.

Note that this check operates on the current channel permissions, not the
guild wide permissions.

The permissions passed in must be exactly like the properties shown under
[`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions")...
knotty agate
#

how can i send a message?
lets say i have a command called !announce, and i want it to send a message in #announcements, how could i make it send a message in #announcements and not respond in the same channel i gave the command?

the only way i know to send messages is

await message.channel.send("announcement!")
slate swan
#

try

channel = client.get_channel() #enter channel id
await channel.send('hello')
knotty agate
#

i assume the channel id is the name of the channel?

slate swan
#

bro

#

the snowflake

heady sluice
# knotty agate how can i send a message? lets say i have a command called !announce, and i want...

You see, message.channel is a discord.TextChannel object, that's why you can use send() on it.
Another way to get a discord.TextChannel like message.channel is to use bot.get_channel(id) or client.get_channel(id), like this:

channel = bot.get_channel(343944376055103488) #343944376055103488 is the id of the discord-bots channel we're in

After you have this channel variable which stores a discord.TextChannel object, you can use send() on this too.

channel = bot.get_channel(343944376055103488)
await channel.send("Hello!")
slate swan
#
Traceback (most recent call last):
  File "c:\Users\bopae\Downloads\Self made\Random\s4u bot\crypto.py", line 42, in <module>
    client = commands.Bot(command_prefix="-")
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
pls help
cloud dawn
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

How to enable all intents again?

heady sluice
#

discord.Intents.all()

slate swan
#

thx a lot

slate swan
#

Man I just spent a good 10 minutes trying to tell this dude that he has to define a function to call it and that calling a random ass function won’t magically work

heady sluice
#

!e
print("Hello!")

unkempt canyonBOT
#

@heady sluice :white_check_mark: Your eval job has completed with return code 0.

Hello!
slate swan
slate swan
#

I’m still going on with that dude

heady sluice
#

called a random ass function

slate swan
#

He’s wondering why “do_my_bullshit()” doesn’t do what he wants it to do magically

heady sluice
#

you didn't put anything in open_account

slate swan
#

Your code 💀

heady sluice
#

put there what you want it to do

slate swan
heady sluice
#

I usually just put pass if I don't know yet

slate swan
#

Sigma grindset

#
def open_account():
   pass

you can edit it later

#

or use ellipsis 😳

#

Oh no

#

It’s not gonna magically work since you defined the function

#

why make a function you arent gonna useyert

#

You need to program what you want it to do

knotty agate
#

how can i make my bot give users roles?

cloud dawn
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

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

thanks

regal pulsar
#

help

#

im using reddit's api to send posts from r/tifu

#

sometimes the posts exceed the 4018 character limit

#

im trying to split the paragraph in half and send it in 2 embeds if it does

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

That is qu
regal pulsar
#

i see

#

what is that

#

i need to learn it

#

looks useful

heady sluice
#

!e
print(len("Hello World!") > 2018)

unkempt canyonBOT
#

@heady sluice :white_check_mark: Your eval job has completed with return code 0.

False
cloud dawn
#

!e ```py
text = "That is quite unfortunate."

print(text[:7] + "...")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

That is...
slate swan
regal pulsar
#

i see

heady sluice
slate swan
#

Give up on English too ig

#

Seems a bit hard for you too

#

Hm that was mean

#

Don’t give up on your code

#

Learn

#

bruh

#

Bruh 💀

#

command example ?

#

What is your problem

#

You don’t know how to code?

#

We’ll go and fix that yourself

#

Eh sorry I’ve had a lot of bullshit today

regal pulsar
#

hmm one more question

slate swan
regal pulsar
#

i need to .split the paragraph while keeping the word

slate swan
heady sluice
regal pulsar
#

for example:

selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""
selftext_list = selftext.split(" ")
num = len(selftext_list) // 2
txt = selftext_list[:num][-1]
txt1 = selftext.split(txt)
desc1, desc2 = txt1[0], txt1[1]
#

this is what i have rn

slate swan
#

Raise the error

regal pulsar
slate swan
daring olive
#

hi

slate swan
velvet compass
#

hi mina

heady sluice
#

!e

selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""
print(selftext[:40])
print(selftext[41:])
regal pulsar
heady sluice
#

god I messed up

slate swan
#

hi mina, hi brad

daring olive
#

hihi

regal pulsar
unkempt canyonBOT
#

@heady sluice :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | sit amet nisl suscipit adipiscing biben
003 | um est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
slate swan
#

guys

regal pulsar
#

im getting posts from reddit

slate swan
#

try channel id

#

#bot-commands

regal pulsar
#

so some will be longer than others

slate swan
#

It would redirect you to bot commands if you couldn’t use it here

heady sluice
slate swan
heady sluice
#

it is

slate swan
#

you guys are just showing index slices

heady sluice
#

it's literally showing the other how stuff works

slate swan
#

when its really not that hard?

slate swan
#

bro

#

its literally just indexingyert

slate swan
#

its not related to the topic of this channel.

heady sluice
#

sure

regal pulsar
#

the lorem ipsum stuff was just a sample text

slate swan
#

bro

#

its index slicing

heady sluice
#

it's not like there are other stuff going on in the channel we could talk about

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

cloud dawn
#

!e ```py
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]

selftext = """
sit amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula
"""

print(list(chunks(selftext, 10)))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

['\nsit amet ', 'nisl susci', 'pit adipis', 'cing biben', 'dum est ul', 'tricies in', 'teger quis', ' auctor el', 'it sed vul', 'putate mi ', 'sit amet m', 'auris comm', 'odo quis i', 'mperdiet m', 'assa tinci', 'dunt nunc ', 'pulvinar s', 'apien et l', 'igula\n']
heady sluice
#

except Nakime's syntax errors

regal pulsar
# slate swan He was asking in context of his discord bot

    @commands.command()
    async def tifu(self, ctx: commands.Context):
        tifu = random.choice(tifu_list)
        try:
            embed = disnake.Embed(title=f"__{tifu.title}__", url=tifu.url, description=tifu.selftext, color=0x00FF00)
            embed.set_author(name=ctx.author, icon_url=ctx.author.avatar)
            embed.set_image(url=tifu.url)
            await ctx.channel.send(embed=embed)
        except:
            selftext = str(tifu.selftext)
            selftext_list = selftext.split(" ")
            num = len(selftext_list) // 2
            txt = selftext_list[:num][-1]
            txt1 = selftext.split(txt)
            desc1, desc2 = txt1[0], txt1[1]
            embed = disnake.Embed(title=f"__{tifu.title}__", url=tifu.url, description=desc1, color=0x00FF00)
            embed.set_author(name=ctx.author, icon_url=ctx.author.avatar)
            embed.set_image(url=tifu.url)
            await ctx.channel.send(embed=embed)
            embed = disnake.Embed(description=desc2)
            await ctx.channel.send(embed=embed)

paper sluice
#

💀

regal pulsar
#

this works

#

but

#

the word i split it by gets cut

heady sluice
#

I see it

#

Unknown interaction

slate swan
#

the interaction is invalid or expired

#

?

olive osprey
#

what

slate swan
#

idk

heady sluice
#

at which line does the error appear @slate swan

#

.

slate swan
heady sluice
#

and realised it has to be at the start cuz the whole code is surrounded by error-eating try excepts

slate swan
#

how to make it send User not muted when the user is not muted

heady sluice
#

nah

heady sluice
paper sluice
#

value = '{}'.format(member.mention) pithink

slate swan
#

thx=)

heady sluice
#

...

#

value = member.mention
@slate swan

#

and f-strings are cool

slate swan
paper sluice
slate swan
#

ik

#

lol

slate swan
#

I am back

#

Mute was devastating

slate swan
#

Yes

#

😻

paper sluice
#

cool

slate swan
#

im not sure if you should talk about your infractions here as it probably should stay confidential and its not on topic.

final iron
#

You can talk about your warns

slate swan
#

i doubt

#

and my point still stands lol

final iron
#

Not in the rules

slate swan
#

doesnt mean its allowed

final iron
#

I mean...

#

It kinda does

slate swan
#

bro

#

it really doesn't

brisk dune
#

Let's just use common sense here and not talk about it...

slate swan
#

i agree

final iron
#

Therefore nothing is stopping us from talking about it

brisk dune
# final iron It's not in the rules

Nobody gains anything from it, nobody loses anything if it is not spoken about. With the benefit of the doubt given, it's equably good (arguably better) to not talk about it.

#

Plus, not really related to discord bots...

sacred plume
#
        background = Image.open("background.jpg")
        asset = user.avatar_url_as(size = 128)
        data = BytesIO(await asset.read())
        pfp = Image.open(data)
        pfp = mask_circle_transparent(pfp, 4)

        pfp = pfp.resize((209, 209))
        background.paste(pfp, (385, 160), pfp)
        background.save("welcome.png")
        await ctx.send(file=discord.File("welcome.png"))

Hi ! How can I send background without saving it as welcome.png ?

little ivy
slate swan
#

no

#

its making the view not timeout

#

the view class has it already as well lol

#

it makes it persistent because of the button custom ids

#

!d discord.ui.Button.custom_id

unkempt canyonBOT
#

property custom_id```
The ID of the button that gets received during an interaction.

If this button is for a URL, it does not have a custom ID.
rare saddle
#

How to make the bot become a speaker when entering the stage channel?

buoyant zodiac
#
@commands.command()
    async def whitelisted(self, ctx):
        if ctx.author is not ctx.guild.owner:
            return await ctx.reply("You must be the guild owner to use this command")
        else:
            whitelisted = db.find_one({"_id": ctx.guild.id})["whitelisted"]
            embed = discord.Embed(title="Whitelisted", description="",color=0x2f3136)
            for i in whitelisted:
                member = self.bot.get_user(i)
                if member.id == 933235685001924618 or 957064940974407700:
                 embed.description + f":Badge_Developer: - {member.mention}\n"
                else:
                 embed.description + f":Discord_Members: - {member.mention}\n"
            embed.set_footer(text="Guild Owners are automatically whitelisted.")
            await ctx.reply(embed=embed)
``` theres poeple in the whitelisted but its not bringing anything up
ornate aspen
#

Hi

#

Whats is a good linux distro?

lunar quail
#

!or-gotcha

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
pseudo portal
#

Yo can someone pls explain whats goin wrong 😅

tidal hawk
#

Yo huh

#

Basically I used slash command and it gave me old code results

#

Like I've updated it 15 minutes ago, but it still gave me the old version

#

It doesn't even exist

buoyant zodiac
slate swan
#

TypeError: 'in <string>' requires string as left operand, not list

slate swan
slate swan
# slate swan Code and full traceback

Traceback (most recent call last): File "C:\Users\ydzja\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "C:\Users\ydzja\Desktop\Dox Defender Developpement\main.py", line 200, in on_message if [str(ctx.guild.id)] not in ("antigrabify.json"): TypeError: 'in <string>' requires string as left operand, not list

Code

`@bot.listen()
@commands.has_permissions(administrator=False)
async def on_message(ctx):

Linkembed = discord.Embed(description="blabla.", title="this is an alert")
Linkembed.set_footer(text=f"yes | from {ctx.author}")

with open("antilinks.json", "r") as f:
    setAntiLinks = json.load(f)

if [str(ctx.guild.id)] not in ("antilinks.json"):
    setAntiLinks[str(ctx.guild.id)] = "off"

with open("antilinks.json", "w") as f:
    json.dump(setAntiLinks, f, indent=4)
    

if "https://" in ctx.content.lower():
    if setAntiLinks[str(ctx.guild.id)] == "on":
        await ctx.delete()
        await ctx.channel.send(embed=Linkembed)
        await bot.process_commands(ctx)`
#

in antilinks.json :

#

@slate swan

#

I see the problem

#

First of all

#

Your doing “[string]”

#

Wait I’m confusing myself

#

I know what you have done wrong

#

Basically your saying if a list is in a string

#

Which is a no go

#

And you can’t open a file using (“file name”)

#

    @tasks.loop(seconds = 5) # repeat after every 10 seconds
    async def myLoop():
        with open("count.stonks","r") as f:
            count = int(f.read())
            f.close()
        channel = client.get_channel(903918973408665620)
        channel.send("{count}")

    myLoop.start()

gives error

Traceback (most recent call last):
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 753, in myLoop
    channel.send("{count}")
AttributeError: 'NoneType' object has no attribute 'send'```
#

It hasn’t retrieved the channel object

#

how do i fix that

mortal dove
#

clients can't find channels iirc, is it a bot?

slate swan
#

Ffs

mortal dove
#

?d commands.Bot.get_channel

slate swan
mortal dove
#

bruh

pseudo portal
#

why does it give me error but still work think

pseudo portal
pliant gulch
slate swan
unkempt canyonBOT
pseudo portal
mortal dove
#

oh haha

slate swan
#

It returns a Nonetype if no channel is found

pseudo portal
slate swan
#

It expects a reply

pseudo portal
slate swan
#

I don’t mess with slash commands but it seems the be the same principle of interactions

slate swan
pseudo portal
pseudo portal
# slate swan Yep

still seems to b buggin 😅 i am gettin a ton of error messages, can i send a scrn shot?

pseudo portal
#

idek whats goin on 😅

slate swan
#

Might be a bug with the slash command library your using

#

    @tasks.loop(seconds = 5) # repeat after every 10 seconds
    async def myLoop():
        with open("count.stonks","r") as f:
            count = int(f.read())
            f.close()
        channel = self.bot.get_channel(903918973408665620)
        channel.send("{count}")
    myLoop.start()
Unhandled exception in internal background task 'myLoop'.
Traceback (most recent call last):
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 752, in myLoop
    channel = self.bot.get_channel(903918973408665620)
NameError: name 'self' is not defined
#

how tf

pseudo portal
slate swan
#

That has slash commands now?

pseudo portal
slate swan
#

Also await the channel.send

slate swan
pseudo portal
#

'ApplicationContext' object has no attribute 'reply' think

slate swan
#

but idk how to implement it

#
    @tasks.loop(seconds = 5) # repeat after every 10 seconds
    async def myLoop(self):
        with open("count.stonks","r") as f:
            count = int(f.read())
            f.close()
        channel = self.bot.get_channel(903918973408665620)
        channel.send("{count}")
    myLoop.start()

just gives

  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
TypeError: myLoop() missing 1 required positional argument: 'self'```
#

You don’t need self

#

bot.get_channel works fine

#

Or you can use bot.fetch_channel

#
  File "C:\Users\allan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "C:\Users\allan\OneDrive\Documents\mootbot\cogs\Commands.py", line 752, in myLoop
    channel = bot.get_channel(903918973408665620)
NameError: name 'bot' is not defined
slate swan
#

It’s your commands.Bot() variable

pseudo portal
#

AttributeError: 'ApplicationContext' object has no attribute 'reply' ofc it does..? 😅

slate swan
#

import discord
from discord.ext import commands
import asyncio
import logging
import datetime
import os
import re
import random
import json
import requests
from random import choice
import time
from discord.ext import tasks

client = discord.Client()

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

    @tasks.loop(seconds = 5) # repeat after every 10 seconds
    async def myLoop(self):
        with open("count.stonks","r") as f:
            count = int(f.read())
            f.close()
        channel = self.bot.get_channel(903918973408665620)
        channel.send("{count}")
    myLoop.start()


    @commands.command(name="name")
    async def name(self,ctx, name=None):
        channel = int(968972997031506002)
        channel2 = self.bot.get_channel(channel)
        await channel2.edit(name=f"{name}")

def setup(bot):
    bot.add_cog(Commands(bot))```
#

thats my entire code for the cog

pseudo portal
boreal ravine
#

yeah

slate swan
#

bot is already defined so why is it saying it isnt

boreal ravine
#

but which library

slate swan
final iron
boreal ravine
slate swan
pseudo portal
final iron
slate swan
final iron
#

It's already 100% going to be an integer

slate swan
#

because thats just placeholder

pseudo portal
slate swan
boreal ravine
buoyant zodiac
#
await msg.add_reaction(":enemy_yes:")
``` i did this wrong didnt i
boreal ravine
buoyant zodiac
#

not the reaction part but the emoji part

slate swan
pseudo portal
# boreal ravine show me `crypto`, the function part
@bot.slash_command(guild_ids=[956267961751044146], description="We've all heard of it, but what does it actually mean?")
async def crypto(ctx):
        embed = discord.Embed(
            title='Cryptocurrency',
            description="[text block]",
            colour=discord.Colour.blue()
        )
 
        embed.set_footer(text='For anything else, just use the /help command.')
        embed.set_author(name='Night Wolf', icon_url='[link.jpg]')
        embed.add_field(name='Getting Started:', value='[How crypto actually works →]([link.jpg] \"Watch here\") [How to get started with Crypto →]([link.jpg] \"Read More\")',
                        inline=True)
        embed.add_field(name='Also Try:', value='!crypto-mining, !blockchain, !bitcoin, !investing, !buy-crypto', inline=False)
        embed.set_image(url='[link.jpg]')

i replaced all the links

buoyant zodiac
buoyant zodiac
#

if u wouldnt mind

pseudo portal
boreal ravine
sly hamlet
#

In 2.0 how can I make a specific / command to only one server

slate swan
pseudo portal
boreal ravine
#

and what type of command? message command? text command? slash command? user command?

boreal ravine
pseudo portal
slate swan
boreal ravine
tight orbit
#

Hey, I'm trying to get a program to send a webhook. I've tried searching for solutions but they all use a module called "discord-webhook" and when i try to use it, it says no module named "discord_webhook" exists

boreal ravine
#

maybe it's an internal bug, try asking in the py-cord server if you haven't already

pseudo portal
boreal ravine
tight orbit
pseudo portal
boreal ravine
#

did you restart your IDE?

tight orbit
boreal ravine
#

you said discord-webhook 🤔

tight orbit
pseudo portal
boreal ravine
#

messages don't have titles.. nor descriptions

pseudo portal
# boreal ravine api for what?

uugh idek im lost now. oh wait, na, u were askin if im usin requests to api, i thought u said i "should" do that 😂 sorry mb

boreal ravine
#

👍

pseudo portal
#

so now that ik im not 😄 do u know what can b causing those errors? 😄

slate swan
#
@client.event
async def on_message(message):
        results = collection_prefix.find({"guild_id": message.guild.id})
        for result in results:
            pass
        if result["prefix"] == "":           
                client.command_prefix = dprefix
                await client.process_commands(message)
        else:
            client.command_prefix = result["prefix"]
            await client.process_commands(message)

hello im currently trying to do a custom guild prefix and im having issues to check if the value guild_id is none and when its none it should insert the guild into the database
when i try to use the variable result it says local variable 'result' referenced before assignment because the list is empty

rare saddle
#

How to move the bot to the stage channel speakers so that it can play music?

boreal ravine
pseudo portal
karmic totem
boreal ravine
pseudo portal
#

lads, shld i just stick with slash cmmnds or add prefix commands as well? xD

slate swan
boreal ravine
pseudo portal
boreal ravine
boreal ravine
unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command")...
slate swan
boreal ravine
slate swan
#

doesnt work

boreal ravine
#

well it should work

flat solstice
#

In my bots DB I'm storing a channel ID for where I want my bot to greet members, a message I want members to be greeted with and a Boolean for if the guild has member greetings enabled. My original plan for doing this was so that admins could toggle if they want greetings enabled or not without erasing their greeting message or their greeting channel however I have since realized I could remove the Boolean and remove the greeting channel and just run a check on if the channel exists or not as the deciding factor for if the greeting message gets sent, what do you guys think; should I keep or remove the Boolean

slate swan
#

when i try to print results

<pymongo.cursor.Cursor object at 0x000002726CEF7610>
#

maybe i should try find_one

#

i think thats the error

boreal ravine
#

yeah

#

imo don't use find if you aren't getting lots of documents

slate swan
#

okay

slate swan
#

yeah that was the problem

flat solstice
boreal ravine
mortal dove
#

I'm getting this from a discord.py hybrid command, not really sure why. Anyone know?
ServerDisconnectedError: Server disconnected
I can send the whole error if it would help, but it gets to the end of the command, until a ctx.send() at the end.

silver agate
#

how do I turn of view message history?
Lock is easy but I cant find the overwrite for it

mortal dove
#

Restarted bot, discord, synced commands, etc.

rare saddle
#

How to make the bot be a speaker when connecting to the channel

slate swan
mortal dove
#

indeed

slate swan
#

weird i see no reason why it would

mortal dove
#

Yeah :/

#

My internet is usually very good, too.

slate swan
#

nah that really shouldnt be an issue

boreal ravine
#

it should

#

you need internet to use aiohttp

slate swan
#

bro you see how i said really

boreal ravine
#

chill out

slate swan
boreal ravine
rare saddle
#

@flat solstice And if the bot is a moderator of the stage channel, can he enter and become a speaker himself?

flat solstice
silver agate
#

ahhh thanks sifte

slate swan
#

when i try to edit a channel name this happens despite it having manage channel permission;

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

but when it has administrator it works? why can't it edit channel names with the manage channel perm?

silver agate
brisk dune
#

I'm guessing the Manage Events permission in the Discord application configurator isn't for bot.event(), but rather actual "events" in a discord server?

boreal ravine
#

yes

#

bot.event is for gateway events/custom made events

boreal ravine
silver agate
#

how to add the bot status "add to server" ?

#

like that

slate swan
silver agate
#

I did

#

its not working @slate swan

slate swan
#

idk

torn sail
#

you need to configure a default invite

silver agate
#

o: ?

torn sail
#

inside oath its called "general"

silver agate
#

yer

brisk dune
#
import discord
from discord.ext import bridge, commands
import os
from dotenv import load_dotenv


# Secrets
load_dotenv("secrets.env")
TOKEN = os.getenv("DISCORD_TOKEN")
PREFIX = os.getenv("DISCORD_PREFIX")


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


# Initialize
bot = bridge.Bot(intents=intents, command_prefix=PREFIX)


# Commands
@bot.bridge_command()
async def reply(ctx: bridge.context.BridgeContext):
    await ctx.reply("Hello!")


@bot.bridge_command()
async def reply2(ctx: bridge.context.BridgeContext):
    await ctx.reply("Hi!")


# Run
bot.run(TOKEN)

My second slash command won't appear in the slash commands menu when I type /. The first one works fine, but the second one doesn't. (I'm using PyCord 2.0.0 btw). The prefixed version works, but the slash command version doesn't...

silver agate
torn sail
brisk dune
torn sail
#

does pycord to it for you?

silver agate
torn sail
#

👍

brisk dune
#

But adding specific guild_id(s) to the decorator worked

#

I just wanted to do it without that

torn sail
brisk dune
sour inlet
#

how do I get the voice channel that the bot is in?

#

ctx.bot.voice.channel doesn't work

#

nvm it's ctx.voice_client.channel.members

boreal ravine
unkempt canyonBOT
sour inlet
#

thanks but my thing works fine

#

unless it's like super intensive? it checks how many people are in it each second

#

will that impact performance at all?

#

or should I just use events to check when members change

boreal ravine
sour inlet
#

oh wait sorry I mistyped

#

I wanted the voice channel that the bot was in in order to get the members

#

it's ctx.voice_client.channel I meant

nova wave
boreal ravine
nova wave
#

I need some help brother can't do thiss all alone

slate swan
#

Hi back

feral lichen
#

Hello, I have a question. I've been trying to read the docs for Guild.audit_logs(). and im still having trouble. How would I get this to see if the past two logs and see if the two logs were channels being deleted? ```py
@bot.event
async def on_guild_channel_delete(cha):
async for entry in cha.guild.audit_logs(limit=2, action=discord.AuditLogAction.channel_delete):
print("2")

boreal ravine
#

why do you wanna check again

sly hamlet
#
Warning (from warnings module):
  File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\cogs\api.py", line 28
    start_loop()
RuntimeWarning: coroutine 'DiscordListsPost.start_loop' was never awaited``` ```py
async def start_loop():
        await self.api.start_loop()
        await DiscordListsPost.start_loop()
        print("Post Count")

    start_loop()``` how can i fix this?
sly hamlet
#

so ```py
async def start_loop():
await self.api.start_loop()
print("Post Count")

await start_loop()```
torn sail
#

When do u need to start it

sly hamlet
#

when the code starts

torn sail
sly hamlet
#

yes

torn sail
#

Override cog_load as a async function and start it there

sly hamlet
#

sorry i do not know how to

torn sail
#

async def cog_load(self):

#

Then new line indents and await the functions

torn sail
sly hamlet
#

so ```py
async def cog_load(self):
await self.api.start_loop()
print("Post Count")

cog_load()```
torn sail
#

Don’t call cog_load

#

The lib will call it when the cog is loaded

sly hamlet
#

ok

torn sail
#

Also you might have to use self.bot.loop.create_task

sly hamlet
# torn sail The lib will call it when the cog is loaded

i get this ```py
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 53, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 46, in main
await bot.load_extension('cogs.api')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 869, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 808, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.api' raised an error: AttributeError: ('loop attribute cannot be accessed in non-async contexts. ', 'Consider using either an asynchronous main function and passing it to asyncio.run or ', 'using asynchronous initialisation hooks such as Client.setup_hook')```

torn sail
#

Huh then looks like I was wrong

sly hamlet
#

so now what?

torn sail
#

Not sure. Hopefully someone else can come along

sly hamlet
#

ok

supple thorn
#

anyone know what style of docstrings disnake uses

torn sail
sage otter
#

I also had something like that earlier

#

I just circumvented by manually grabbing the event loop and using that instead of the loop attr for Bot

#

asyncio.get_running_loop().create_task()

#

You can either put in the cogs init

#

Or the cog_load method

slate swan
#

and its ofcourse same as discord.py ones which uses sphinx autodoc

feral lichen
slate swan
#

sending a message will always need an await or are there exceptions?

final iron
#

Anything calling the API basically needs to be awaited

slate swan
#

😳 unless you make requests to the API manually using requests

#

will there ever be certain exceptions?

slate swan
final iron
#

Probably

slate swan
final iron
#

There might be a few edge cases, but nothing to send messages

slate swan
#

nah, anything which makes a request to the API is an awaitable in discord.py since they use aiohttp and its all async

feral lichen
#
@bot.event
async def on_guild_channel_delete(cha):
     async for entry in cha.guild.audit_logs(limit=2, action=discord.AuditLogAction.channel_delete):
       print("2")   ``` how would i get this to grab the last two logs and see if they were channel_delete? ``nvm i solved my own question``
slate swan
#

How can I pause what the bot is playing in voice channel?

boreal ravine
#

Pause your voice client

supple thorn
#

I did and it's numpy style docstring but weird

feral lichen
#

man no ones answering 😔

supple thorn
#

It's like 95% numpy and 5% something else

#

Which i can't find what this mixed style numpy is

supple thorn
slate swan
slate swan
mortal dove
buoyant zodiac
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style
chaining. Can only be up to 25 fields.
slate swan
sly hamlet
#

??

slate swan
#

?

sly hamlet
#

I do not get what you mean because I do not remember seeing anything like that in the original code

slate swan
#

what

sly hamlet
#

Exactly what I said I do not remember seeing anything on the lines of coro and recursion not even exactly 100% sure what that is

cold sonnet
#
#normal function
def say():
    print("say whaat") 

#coroutine
async def say():
    print("I'm a coro") 
buoyant zodiac
#

how can i add a check to a interaction w discord components

slow fog
buoyant zodiac
#

Okay so i'm doing a thing with buttons but i only want the author of the person that invoked the command to be able to use the buttons not everyone

cold sonnet
#

in a wait_for?

slate swan
#

is there a way to collapse embeds from a message ?

#

using pycord

slate swan
#

like

#

suppose someone sends a message which embeds something (like a link)

#

i wanna collapse the embed

#

usually you would use Message.edit(embeds=[]) but i doubt if that would work for other user's message

#

It won't

#

You can't edit other people's messages like that (thankfully)

stone beacon
#

There are probably modules out here that add check functionality though. Discord recently added a nice permission update for slash commands as well

#

Although idk if the libraries added support for it yet. Idek when the update was

slate swan
unkempt canyonBOT
#

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`...
slate swan
#

There is a suppress kwarg

#

Set that to True and they will collapse.

slate swan
#

If the bot has manage_messages permissions, yes

#

alr dope thanks

#

Surprised they haven't made a separate method to prevent confusion

buoyant zodiac
#

How to send files?

slow fog
abstract kindle
#

can someone elp me setup slash commands

#
Traceback (most recent call last):
  File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\main.py", line 16, in <module>
    tree = app_commands.CommandTree(bot)
  File "C:\Users\beege\Documents\GitHub\EconomyDiscordBot\venv\Desktop\Coding\lib\site-packages\discord\app_commands\tree.py", line 131, in __init__
    raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.

Not sure why this is happening

zenith mural
#

can someone please help me with a help command for my bot?

boreal ravine
zenith mural
#
@bot.slash_command(name = "help", description = "Help command for the bot")
async def help(ctx):
    embed = disnake.Embed(title = ' help', description = 'Help command for alaska bot' )
    for command in bot.walk_commands():
        description = command.description
        if not description or description is None or description == "":
            description = 'No Description Provided'
        embed.add_field(name = f"``{command.name}{command.signature if command.signature is not None else ''}``", value = description)
    await ctx.send(embed = embed) ```
#

would this work for help command

zenith mural
#

i treid it, only 2 of my commands showed up

#

i have many more

boreal ravine
#

slash commands?

stiff gorge
#

my bot is online but its not sending any message and not showing any error in the console wht to do ?
it has admin perms

zenith mural
boreal ravine
#

did you sync the commands?

zenith mural
boreal ravine
zenith mural
#

global

boreal ravine
#

yes

zenith mural
#

global

boreal ravine
boreal ravine
tall dust
#

@boreal ravine fyi that website is blacklisted because its often used in an unfriendly way

stiff gorge
slate swan
#

Permissions update I've told you about just came out officially

boreal ravine
stiff gorge
#

yes

boreal ravine
#
  • Does your bot have the message content intent?
  • Do you have an on_message event?
oak oar
zenith mural
stiff gorge
oak oar
slate swan
#

what's wrong?

abstract kindle
#

Do I have to sync the slash commands?

boreal ravine
abstract kindle
#

Just for my guild

oak oar
boreal ravine
#

No

slate swan
supple thorn
slate swan
supple thorn
#

if you dig deep enough into danny's secret folders

supple thorn
oak oar
oak oar
slate swan
abstract kindle
#

@boreal ravine how do I sync the commands just for my guild

#

I don't want to have to wait hours

supple thorn
boreal ravine
abstract kindle
#

when do I run that?

#

Just as a separate command, or on startup?

oak oar
#

python bot is kinda weak in looking for discord.py docs 😔

boreal ravine
oak oar
#

its just harder than using readthedocs imo

boreal ravine
supple thorn
#

mostly because they won't load

#

😔

oak oar
oak oar
supple thorn
#

same

stiff gorge
supple thorn
#

even higher?

oak oar
#

💀

stiff gorge
#

u asked py version right ?

boreal ravine
stiff gorge
#

python = "^3.6"

slate swan
#

where error?

supple thorn
#

that's what you tell us

oak oar
abstract kindle
#

How do you add the command to the tree?

#

How do you reference the command when adding it I mean

boreal ravine
unkempt canyonBOT
#

Hey @zenith mural!

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

abstract kindle
#

How would I format a slash command in a cog?

zenith mural
#

can someone help?

slow fog
abstract kindle
#

I'm off to bed, but if anyone would like to just dm me the way to setup a slash command in a cog that would be sick

sinful wind
#
@slash.slash(
    name = "Register-Steam-Friend-Code",
    guild_ids = guilds
)
async def registerFriendCode(ctx: SlashContext, code: str):
    author = ctx.author
    savedFriendCodes[ctx.author_id] = code
    verificationRole = get(ctx.guild.roles, id = verificationRoleID)
    await author.add_roles(verificationRole)
    await ctx.send("Your Steam friend code is now registered.")

client.run(token)
- discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

Why does it say I am missing permissions? I invited my bot with admin permissions and also used applications.commands

#

To be more specific the Missing Permissions is pertaining to await author.add_roles(verificationRole)

boreal ravine
#

the bots top role is below the authors top role

#

or maybe it doesn't have permissions

sinful wind
#

it was because the bots top role was ranked lowest

#

I did not know the order mattered

spice adder
#

I figured out how to get it from a subreddit, but I'm not really sure what path to take from here

placid skiff
#

are you using a webscraping method?

spice adder
#

I used something similar to that for the reddit part, but no, I am not sure where to begin with that

placid skiff
#

btw you can't get images from that site if there isn't API

#

images are get from a script which connects to a relative path inner the website

spice adder
#

Oh I see, do you happen to have any links to some kind of documentation for how to do that?

#

Actually, I should probably look that up before asking - sorry!

placid skiff
#

No you didn't understand i'm not talkin of a script to get the images i'm talkin about a javascript inside that page that retrieves images somewhere else and there isn't a link to them

spice adder
#

Ah, gotcha

placid skiff
lyric apex
#

Can we get the time when the command was used like i am using mysql for afk command and i want to show that x user was afk x seconds ago

#

<t:7272773:R>

#

Is this form

placid skiff
lyric apex
placid skiff
#

!d discord.Message.created_at

unkempt canyonBOT
lyric apex
#

Not utc

placid skiff
#

it doesn't tell the type, btw it give you a datetime object

#

you can manipulate it however you want

zenith mural
#
@bot.slash_command(name = "whois", description = "shares a users info")
async def whois(ctx, user : disnake.Member = None):

    if user== None:
        user = ctx.author
    
    rlist = []
    for role in user.roles:
        if role.name!= "@everyone":
            rlist.append(role.mention)
    b = ','.join(rlist)

    embed  = disnake.Embed(colour = user.colour, timestamp= ctx.message.created_at)
    embed.set_author(name = f"User Info: {user}"),
    embed.set_thumbnail( url = user.avatar.url),
    embed.set_footer(text = f"Requested By: {ctx.author}",
    icon_url = ctx.author.avatar_url)

    embed.add_field(name = 'ID', value = user.id, inline = False)
    embed.add_field(name = "Joined At: ", value = user.display_name, inline = False)

    embed.add_field(name = "Created At: ", value = user.created_at, inline = False)
    embed.add_field(name = "Joined At: ", value = user.joined_at, inline = False)
    
    embed.add_field(name = f"Roles: ({len(rlist)}))", value = ''.join([b]), inline = False)
    embed.add_field(name = "Top Role: ", value = user.top_role.mention, inline = False)

    embed.add_field(name = 'Bot?', value = user.bot, inline = False)

    await ctx.send(embed = embed)
``` can someone please help me with this whois command it isnt working
placid skiff
#

slash commands in disnake takes up to 1 hour to be registered globally. Please read the docs

stiff gorge
#

why is this not wrking

Traceback (most recent call last):
  File "main.py", line 165, in <module>
    @client.command()
AttributeError: 'Client' object has no attribute 'command'
@client.command()
async def ping(ctx):
    await ctx.reply(f"My API Latency is {round(client.latency * 1000)}ms")
placid skiff
#

show your client instance

slate swan
#

thats for all libraries, not specific to disnake

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result
anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with
this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality
to manage commands...
slate swan
#

What's this supposed to mean? ```py
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 1025, in on_connect
await self.sync_commands()
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/bot.py", line 685, in sync_commands
await self.http.bulk_upsert_command_permissions(self.user.id, guild_id, guild_cmd_perms)
File "/home/runner/Modmail-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 357, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed

clear plinth
#

I'm in a server with a bot that has a neat pop up dialog box, does anyone know what this is called? Here's how it looks on mobile

quick gust
#

its a "modal"

slate swan
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
clear plinth
#

Ty everyone!

green bluff
#

hi so ik with a module i could do Embeds.no_perms

#

but i want to add dots like Embeds.no_perms.perm_level_2

#

like more dots

supple thorn
green bluff
#

like

#

i want to make it

#

hi.hi

supple thorn
green bluff
#

like?

supple thorn
#

Subclass it and make your own method

#

Or whatever you're looking for

green bluff
supple thorn
#

That's not how you subclass

#

Also why are you subclassing object

green bluff
#

idk

#

can you give me an article

#

ive tried looking

#

for some

supple thorn
supple thorn
#

Corey Schafer has some nice videos about OOP

slate swan
#
class MyEmbed(discord.Embed):
    my_property = "this"
``` smthing like this
vale wing
idle laurel
#

im making a multiguild bot, am i best using MongoDB or MySQL fo sorting all the data? im using MongoDB atm

vale wing
idle laurel
vale wing
#

Well wait for the answer there?

idle laurel
#

eyy?

slate swan
#

by default classes subclass the object class

#

you need to actually subclass it yourself in py2 iirc

vale wing
#

I never did

#

So probably no

slate swan
#

the my_property thing yeah, that isn't needed

vale wing
#

Ok

slate swan
vale wing
supple thorn
vale wing
#

😳

slate swan
paper sluice
supple thorn
#

Why not a sexy duck

paper sluice
supple thorn
#

😳

slate swan
paper sluice
#

.... ducky_australia

slate swan
supple thorn
slate swan
supple thorn
#

Squidward with tiny bumps

slate swan
#

bro

paper sluice
#

burn octopus

boreal ravine
vale wing
#

Static is like "accessible with class without creating an object" and class var is specifically a static variable of a class

paper sluice
#

static also means that the variable cannot be changed, but in python it can be changed

slate swan
vale wing
#

Most of languages have final modifier

slate swan
#

what it?

paper sluice
slate swan
supple thorn
unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

and yeah youre missing intents hence why your AbstractEventLoop stopped

#

there is an error in the line with the token

#

in <module>

supple thorn
#

@slate swan yeah reset your token

#

I just now saw

slate swan
#

read the full error, reset your token

slate swan
minor totem
jade tartan
#

Can someone help me with my code?

slate swan
#

the custom exceptions say it all why dont people listen to them😔

slate swan
# slate swan

i tried to make a custom prefix and when i finished i got this

vocal plover
# slate swan

fyi, you censored the public bit of the token and left exposed the bit that is actually private

jade tartan
minor totem
boreal ravine
slate swan
minor totem
minor totem
# slate swan i`m reset

While you're at the dashboard, can you now enable the intents you're trying to use? The message intent recently so that you need to enable in on the dashboard

jade tartan
#

like this

minor totem
#

You need to store the warning then, is that what you want help with?

jade tartan
#

Nope its not warn cmd its edit bio profile cmd where the user can edit their bio in their profile

#

Am trying to make like this

quaint epoch
#

bots can't see bios

minor totem
supple thorn
#

Bota?

quaint epoch
#

that's probably a Client object

slate swan
#

thats probably just given

quaint epoch
#

and even if they could, you can't someone elses bio

#

even with the regular discord client

slate swan
#

its a api limitation so it really doesnt matter

quaint epoch
#

now, if you created bios that are not the discord bios, like store them in a database and edit them, it might work

slate swan
#

thats probably the case.

quaint epoch
#

cya

uncut comet
#

hey how can i see who someone replied to in my bot?

quaint epoch
uncut comet
#

i mean like say i took that message you just sent

grim oar
#

check message.reference

uncut comet
#

how can i see who it replied too

quaint epoch
uncut comet
#

so me in this case

#

thank you

quaint epoch
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of
type MessageType.pins_add, crossposted messages created by a
followed channel integration, or message replies.

New in version 1.5.

quaint epoch
#

it returns None in some cases, so just use a check

uncut comet
#

ok ok

jade tartan
#

i am talking about biograpghy no bios thing that your talking about

boreal ravine
quaint epoch
jade tartan
boreal ravine
#

About me's can't be that long

jade tartan
#

and explain

quaint epoch
slate swan
#

How to use on_message inside cogs? discord.Cog.listener? If so, do I do: @commands.Cog.listener()?

quaint epoch
boreal ravine
boreal ravine
#

optional

quaint epoch
boreal ravine
#

but required if the method name isn't an event

quaint epoch
#

like if you had multiple listeners for the same event

#

but lets be real, no insane barbarian would use multiple on_message events.

supple thorn
quaint epoch
jade tartan
#
  File "c:\Users\thoma\OneDrive\Things\Documents\discord server bot\Bot2.py", line 6, in <module>
    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)```
#

nvm i figured it out

#

nope i have not

#

please help

#

Resolved

junior verge
#
@client.command(name="setup")
async def setup(ctx):
    await ctx.send("Starting setup! What does the name of invite channel needs to be?")
    
    msg = await client.wait_for("message")
    await ctx.send(f"Channel named {msg} made")

``` How do I fix this so whenever someone like types test as the channel name it will say Channed named test
#

I changed the code but this gives a weird response too

hushed galleon
#

the check you had earlier was close: py def check(m): return m.content == "" and m.channel == ctx.channel you just need to tweak the return statement so the content doesnt have to be empty, and you might want to make sure the message comes from the same author too

junior verge
#

I mean I don't want anything in the string, I just want people to like name their own channel

hushed galleon
#

well thats the problem, m.content == "" means someone has to send an empty message to pass the check, e.g. by uploading an image

junior verge
#

Hm, how would I then do what I am trying to do?

minor totem
hushed galleon
#

flip the condition around to != or simply write m.content and ... so the check can allow messages with at least one letter

junior verge
#
@client.command(name="setup")
async def setup(ctx):
    await ctx.send("Starting setup! What does the name of invite channel needs to be?")
    member = ctx.author

    def check(m):
        return m.content != "" and m.channel == ctx.channel

    msg = await client.wait_for("message", msg.author == member)
    await ctx.send(f"Channel named {msg} made")
``` Do you mean this?
hushed galleon
#

yeah close, just move that author condition in the check

#

the wait for returns a Message object so to access their actual text afterwards you'd use msg.content, printing {msg} directly is what gives you a "weird response"

junior verge
#

ahh

#

It's giving me this error

#
return m.content != "" and m.channel == ctx.channel
``` Should that be instead of m msg
#

no nvm

hushed galleon
#

you want to have that author condition handled in your check too

junior verge
#

ah

#

the ```py
member = ctx.author

#

or the ```py
msg.author == member

hushed galleon
hushed galleon
junior verge
#

Erm so which one?

hushed galleon
#

the one with two equals signs...

junior verge
#

Yeah sorry

hushed galleon
#

np

flint isle
#

Apparently pystyle dosent work in my console for some reason. I use pydroid 3

junior verge
#

Getting this rn

hushed galleon
#

yeah you need to correct the variable you're using after you put it in your check

#

notice how the previous conditions m.content != "" and m.channel == ctx.channel use m for the message (given in your check parameters)

junior verge
#

Yeah I see

#

But where am I not using m though?

hushed galleon
#

i would assume at the end of that line is where you pasted msg.author == member

junior verge
#

You mean m.author then?

hushed galleon
#

yes

junior verge
#
async def setup(ctx, m):
``` Do I define m here too
hushed galleon
#

nah, you only need to check the author inside the check so someone else or a bot can't interfere with the command

slate swan
#

Hi sup

olive osprey
#

hi sparky

junior verge
#

It says that m is not defined tho

hushed galleon
#

you're still doing the comparison outside of the check, and also not passing the check function to wait_for

slate swan
cyan grove
#

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

vale wing
zenith mural
#
@bot.slash_command(name = "whois", description = "shares a users info")
async def whois(ctx, user : disnake.Member = None):

    if user== None:
        user = ctx.author
    
    rlist = []
    for role in user.roles:
        if role.name!= "@everyone":
            rlist.append(role.mention)
    b = ','.join(rlist)

    embed  = disnake.Embed(colour = user.colour, timestamp= ctx.message.created_at)
    embed.set_author(name = f"User Info: {user}"),
    embed.set_thumbnail( url = user.avatar.url),
    embed.set_footer(text = f"Requested By: {ctx.author}",
    icon_url = ctx.author.avatar_url)

    embed.add_field(name = 'ID', value = user.id, inline = False)
    embed.add_field(name = "Joined At: ", value = user.display_name, inline = False)

    embed.add_field(name = "Created At: ", value = user.created_at, inline = False)
    embed.add_field(name = "Joined At: ", value = user.joined_at, inline = False)
    
    embed.add_field(name = f"Roles: ({len(rlist)}))", value = ''.join([b]), inline = False)
    embed.add_field(name = "Top Role: ", value = user.top_role.mention, inline = False)

    embed.add_field(name = 'Bot?', value = user.bot, inline = False)

    await ctx.send(embed = embed)
``` its been over 3 hours since i coded this and its still not shown up in my bots slash commands, could someone please help me?
vale wing
vale wing
#

This disnake?

zenith mural
zenith mural
hushed galleon
vale wing
#

Try to parse a list with your guild id to test_guilds kwarg of bot constructor

bot = commands.Bot(..., test_guilds=[12345])```
zenith mural
#

alr, ty

#

i could add more than 1 servers ID in that right?

vale wing
#

Yeah

zenith mural
#

alr

#

just by adding commas?

vale wing
#

I don't know if the commands will still be registered for non test guilds

vale wing
zenith mural
#
@bot.slash_commmand(name = 'mute', desrciption = 'Mutes The Specified User')
@commands.has_permissions(manage_messages = True)
async def mute(ctx, member: disnake.Member, *, reason = None):
    guild = ctx.guild
    mutedRole = disnake.utils.get(guild.roles, name = "muted", case_insensitive = True )
    if not mutedRole:
        mutedRole = await guild.create_role(name = "muted")

        for channel in guild.channels:
            await channel.set_permissions(mutedRole, speak = False, send_messages = False, read_message_history = True, read_messages = True)
    await member.add_roles(mutedRole, reason = reason)
    await ctx.send(f'Muted {member.mention} for {reason}')
    await member.send(f'You were muted in the server {guild.name} for {reason}')
``` btw im getting an error with this mute command, mind helping me?
#

ill show you the error hold up

vale wing
#

why not just timeout

zenith mural
zenith mural
#

point

vale wing
#

I never did non cog implementation in disnake so not sure if that decorator exists but I have a suspect that it does

zenith mural
zenith mural
#

oh

zenith mural
vale wing
#

You might've accidentally imported it from wrong lib

#

Nvm

zenith mural
#

lol

vale wing
#

!d disnake.ext.commands.Bot.slash_command

unkempt canyonBOT
#

@slash_command(*args, **kwargs)```
A shortcut decorator that invokes [`slash_command()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.slash_command "disnake.ext.commands.slash_command") and adds it to
the internal command list.
vale wing
#

This thing exists

zenith mural
#

what is this

vale wing
#

Basically what you did

zenith mural
#

alr nvm

vale wing
#

I don't know why you receive AttributeError

vale wing
#

Well I am bad at explaining stuff in english 😩

junior verge
#

The check=check

zenith mural
#
@slash_command(*args, **kwargs)
#

where does this go?

slate swan
#

its a kwarg in wait_for

vale wing
#
bot = commands.Bot(...)

@bot.slash_command(...)
async def cmd(...)```
#

I kinda confused you sorry

zenith mural
#
@bot.slash_commmand(name = 'mute', desrciption = 'Mutes The Specified User')
#

that instead of this?

vale wing
#

You made a typo

stiff gorge
#

My bot is online but not responding how can i fix this ??

vale wing
#

That's why lmao

zenith mural
#

wdym 3 m's

maiden fable
vale wing
#

You typed commmand instead of command

zenith mural
#

oh LMAO

vale wing
#

That's why it's not working

zenith mural
#

that was stupid of me

#

lmao

#

alright its running now

#

thanks for the help

vale wing
stiff gorge
#

its big

vale wing
#

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

vale wing
#

Just make sure to remove the token

zenith mural
#

@vale wing so now the command will take 1 hour to get updated?

stiff gorge
#

or ill just send the important stuff ? ill remove the cmnds frm middle as there is no mistake there

vale wing
zenith mural
#

ig ill add them to test first

vale wing
#

I suspect you have issues with on_message, could you send it here @stiff gorge

#

Oh god

#

Use pasting service pls

stiff gorge
#

ok

maiden fable
vale wing
#

Might be prefixes issue

vale wing
stiff gorge
vale wing
#

Read the bottom text of that embed

#

You clearly didn't read anything and just went to link

stiff gorge
vale wing
#

keep_alive wtf is that

#

When does it occur

maiden fable
#

Forgot? :D

vale wing
#

Ah yes

idle laurel
#

is it possible to stop certain servers using specific commands? i know ill be able to run it in a if linked with a database but not sure if there was an easier way?

maiden fable
#

!pypi keep_alive

unkempt canyonBOT
maiden fable
#

Lmaooo this also exists

stiff gorge
# vale wing `keep_alive` wtf is that
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def main():
  return "Your bot is alive!"

def run():
    app.run(host="0.0.0.0", port=8080)

def keep_alive():
    server = Thread(target=run)
    server.start()
vale wing
#

!d discord.ext.commands.Bot.check

unkempt canyonBOT
#

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

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

cheers

vale wing
#

@stiff gorge I have found a lot of weird stuff in your code so um do you receive your on_ready print

stiff gorge
#

yes

vale wing
#

And it doesn't respond to commands?

stiff gorge
#

no

maiden fable
#

@stiff gorge do u have an event deco?

vale wing
#

Do you have

@bot.event
async def on_message(...)```
Somewhere in your extensions?
stiff gorge
slate swan
#
@commands.Cog.listener()
async def on_message(self, mes): 
     ...```
stiff gorge
#

i had updated to the latest py version today

slate swan
#

oh wait you got disnake huh

stiff gorge
#

i had updated to py 2.0 but the bot was showing many errors so i made it to dyp

stiff gorge
#

yes

slate swan
# stiff gorge yes

you need to enable the message content intent in that case

intents = discord.Intents.default()
intents.message_content = True
slate swan
stiff gorge
slate swan
#

Lol

#

it means you're not using 2.x

pseudo portal
#

yo anyone worked with hybrid commands?

slate swan
#

Code

#

because: discord.py 2.0 has changed Member.avatar_url to Member.avatar.url

#

and it would be ideal to use display_avatar since avatar sometimes may return None (if the profile picture is discord's default)

#

no

#

Use disnake

#

Hi sparky

#

Hi 👋

slate swan
#

ye

#

lovely

slate swan
#

welcome

slate swan
slate swan
#

Nice

pseudo portal
slate swan
pseudo portal
#

im pretty new with python so strugglin quite a bit 😅

slate swan
supple thorn
#

Why

pseudo portal
slate swan
supple thorn
#

What do you mean doesn't work

pseudo portal