#discord-bots

1 messages · Page 560 of 1

manic wing
#

it looks fine from what I can see.

slate swan
#

^
SyntaxError: invalid syntax

File "<stdin>", line 1

manic wing
#

line 1. This indicates your intepreter is fucked or something. restart your ide?

#

idk man its 1 and im doubting myself

slate swan
#

wym LMFAO

#

so wait u dont see anything wrong with it

manic wing
#

it says invalid syntax, line 1. Unless you have a command on line one, just restart your ide

#

i sometimes get this on visual studio code

slate swan
#

ight lemme restart

#

YEA

#

IT WORKS NOW ty dude

#

@manic wing thanks man appreciate it

manic wing
#

np

visual island
#

you can actually do bot._connection._get_message(message_id) ._connection returns ConnectionState object which has a _get_message() method

#

you might get "access to protected member" warning on some IDE tho

brisk kiln
#

Say please what is iteration ?

lament trail
#

iteration is looping through something

patent lark
# brisk kiln Say please what is iteration ?

like @lament trail said, iteration is looping through things, such as lists.

example:

my_list = [1, 2, 3, 4]
for item in my_list:
  if item == 3:
    print("Found it.")

here i iterate through my_list which contains a list of ints

slate swan
#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
slate swan
#

hm

#

but if i do

#

!d discord.Guild.owner

unkempt canyonBOT
#

property owner: Optional[discord.member.Member]```
The member that owns the guild.
slate swan
#

it says it's a property

maiden fable
slate swan
#

thought so

#

but when you click on discord.Guild it says it's an Attribute

maiden fable
#

Isn't it the same damn thing....?

neon oyster
maiden fable
#

Sorry dude I gotta run rn

slate swan
#

okay can someone help me get started with wait_for

pliant gulch
#

pogchamp Fixed my semaphore ratelimiter

slate swan
#

bru what

pliant gulch
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

ohh i was using Bot

pliant gulch
#

Bot extends Client

#

So it also has wait_for

slate swan
#

yeh ik but i was doing discord.Bot.wait_for

#

and it wasn't working

patent lark
#

👍

brisk kiln
#

What is the “nums”??

#

Say me please!

slate swan
#

okay i have the check part down but now how do i get the message

#

jsut set a variable to self.bot.wait_for("message")

pliant gulch
#

Yes

slate swan
#

thx

#

!rules

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

slate swan
#

!rule 8

unkempt canyonBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

slate swan
#

not what i meant

#

we don't spoon feed is what i'm trying to say

#

do i have to put timeout = None?

#
 @commands.command()
    async def rnum(self, ctx):
        await ctx.reply("please respond with 2 numbers for me to choose a random number from")
        def check(reaction, user):
         return user == ctx.author
        l = await self.bot.wait_for("message",check=check,timeout= 10.0)
        await ctx.send(l)

#

i prolly have to pass message right?

#

no cuz then

inland venture
#
    if user_message.lower() == '*specs':
        embed = discord.Embed(title="Sunflower Duck's PC specs", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
                              description="SSD: M.2 1000GB Hard Drive MOBO: B460M Pro Vdh Wifi GPU: Intel UHD 630 Case: H510 Elite RAM: 16GB CPU: Intel core i5 10400",
                              embed.add_field(name="Field 2 Title", value="It is inline with Field 3", inline=True,
                              embed.add_field(name="Field 3 Title", value="It is inline with Field 2", inline=True,
                              color=0xFF5733)
        await message.channel.send(embed=embed)
        return
#

I need help, it says wrong spacing area

slate swan
#

message:discord.Message

#

?

maiden fable
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
thick hamlet
#

How would you guys go on about making an if statement that checks if two emoji are the same

#
this is what I have rn to add an emote to the database

@client.command()
async def emoteAdd(ctx, name, emote):
  if name in db.keys():
    await ctx.message.channel.send("{0} is already an emote".format(name))
    return
  else:
    db[name] = emote
#

so I used %emoteAdd fight \⚔️

#
Then I use this to send a message with a reaction

@client.command()
async def explore(ctx): 
  if check_survivor(ctx) == True:
    e = discord.Embed()
    e.title = "explore"
    e.set_author(name = ctx.author.name)
    e.set_image(url = "https://i.pinimg.com/originals/89/24/8b/89248bb8543b43bcb8958f0df9d8e8e5.png")
    e.description = "You stumbled upon a building surrounded by zombies"
    message = await ctx.channel.send(embed = e)
    message_player[message.id] = ctx.author.id
    toReact = ['⚔️', '🏃']
    for x in toReact:
      await message.add_reaction(x)
      print(x)
thick hamlet
#
then this to compare the emotes 
@client.event
async def on_reaction_add(reaction, user):
    if reaction.message.author == client.user:
      print("The bot sent the message")
      if reaction.message.id in list(message_player):
        print("The message is in the list")
        if message_player[reaction.message.id] == user.id:
          print("The player owns this message")
          print(reaction)
          print(reaction.emoji)
          if reaction.emoji == db["fight"]:
            await reaction.message.channel.send("{0} chose to fight".format(user.name))
          elif reaction.emoji == db["run"]:
            await reaction.message.channel.send("{0} chose to run".format(user.name))
          else:
             await reaction.message.channel.send("{0} what you did is not an accepted action".format(user.name))
        else:
          await reaction.message.channel.send("{0} this is not for you".format(user.name))
#

My expected answer would be the user chose to fight

#

but this is the output

slate swan
#

dont use a seperate reaction event for that , use wait_for

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

@slate swan i need help with that btw

#

do i do async def rnum(self , ctx, message:discord.Message):

slate swan
#

yes that part

#

i have def check(message, user):
return user == ctx.author

outer violet
#

If I make a database using SQLite would I put it in cogs or?

slate swan
#

you cannot have user as an argument

#

now what am i returning?

#

remove user and return message.author == ctx.author

#

okay

slate swan
#

@commands.command()
    async def rnum(self, ctx, message: discord.Message):
        await ctx.reply("please respond with 2 numbers for me to choose a random number from")
        def check(message):
         message.author == ctx.author
        l = await self.bot.wait_for("message",check=check,timeout= 10.0)
        await ctx.send(l)
#

the part is message:discord.Message

#

obv but just asking if that is right

#

besides the message: discord.Message

modern path
#

!e print("Hello world!")

unkempt canyonBOT
#

@modern path :white_check_mark: Your eval job has completed with return code 0.

Hello world!
modern path
#

does anyone know how to write code on discord? I really don't know :(

slate swan
#

!e
def help():
print("test")
if name == "main":
help()

unkempt canyonBOT
#

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

test
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

modern path
final iron
#

Np!

polar linden
#

i want to make a discord bot with a control panel, so what lib do you all recommend I use for it?

#

(im looking for a gui lib)

boreal ravine
unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
rapid isle
#

Huh, weird

#

After switching from client to using bot, the bug of repeating the greeting thrice is gone

#

pretty sure that the only changes I made was converting the whole thing to bot

supple thorn
#

uh

#

are you looking for help or something

rapid isle
#

Not really

supple thorn
#

alright then

rapid isle
#

Okay, not a bug

#

I had multiple different .py running, all containing the greeting sequence

#

I think

#

Me = dumb

#

That's a relief

outer violet
#

how do i make the bot add a reaction every time a user sends a message after the "thread has been created"?

import discord
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_message(self, message):
        if str(message.channel.type) == "private":
            if message.author == self.client.user:
                return
            else:
                guild = self.client.get_guild(900458404953333808)
                channels = await guild.fetch_channels()
                channel = discord.utils.get(channels, name=str(message.author.name))

                if channel is None:
                    category = discord.utils.get(guild.categories, name="Tickets")
                    
                    channel = await guild.create_text_channel((message.author.name), category=category)

                    await message.author.send("thread has been created")

def setup(client):
    client.add_cog(test(client))
tough lance
#

You can use bot.wait_for in a while loop

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
normal ginkgo
#

How can I make a command to stop a command?

slate swan
#

hey

#

dont use idiot api keys

#

use pywhatkit.playonyt

#

the the input

#

then it will play

#

type pip install pywhatkit

#

then you get that modue

#

then use

#
import pywhatkit

pywhatkit.playonyt("videonameorinput")
#This will play directly mmost relavent video on yt!
#

oh sorryyt

#

sorry for class

gloomy coral
#
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py:415> exception=HTTPException('400 Bad Request (error code: 30032): Maximum number of application commands reached (100).')>
Traceback (most recent call last):
  File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 491, in sync_all_commands
    raise ex
  File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 471, in sync_all_commands
    existing_cmds = await self.req.put_slash_commands(
  File "C:\Users\jason\chad\venv\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 30032): Maximum number of application commands reached (100).
#

WTF DOES THIS MEAN

#

no more slash cmds 😦

#

How can I put a cooldown on a slash command... Also it gives an error while using clean_content so i wanna fix tht

tough lance
#

Which lib are you using

tough lance
slate swan
#

How do I make the bot do something when it's added to a server

#

Like what's the event

tough lance
#

on_guild_join

slate swan
#

And what about leave

tough lance
#

wait

slate swan
#

Ok

tough lance
#

!discord.on_guild_remove

#

!d discord.on_guild_remove

unkempt canyonBOT
#

discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

This happens through, but not limited to, these circumstances...
tough lance
#

@slate swan there

slate swan
#

And join is what you said above

tough lance
#

Yes

slate swan
#

Ok thank you

outer violet
#

how do i define check?

slate swan
#

!d discord.on_guild_join

unkempt canyonBOT
#

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

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

uhhh

#

this?

def check(m):
                        return m.content == message and m.channel == channel
#

@tough lance

tough lance
#

ya

outer violet
#

what does this mean?

import discord
from discord.ext import commands
from datetime import datetime

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

    @commands.Cog.listener()
    async def on_message(self, message):
        try:
            if "*close" in message.content:
                pass

            else:
                if str(message.channel.type) == "private":
                    return
                else:
                    if message.author == self.client.user:
                        return
                    else:
                        user = message.guild.fetch_member(int(message.channel.name))
                        embed = discord.Embed(
                            title="message from mods",
                            description={message.content},
                            timestamp=datetime.utcnow()
                        )
                        await user.send(embed=embed)

        except Exception as e:
            print(e)
            pass

    @commands.command()
    async def close(self, ctx):
        user = ctx.guild.fetch_member(str(ctx.channel.name))
        await user.send("your thread has been closed")
        await ctx.channel.delete()

def setup(client):
    client.add_cog(command(client))
gloomy coral
#

pls help

stable delta
#

is there a specific reason why you're using the channel name to fetch a member?

#

well anyway fetch_member fetches a member using the member's user id

spiral frigate
#

How can I get this information
on how many servers the bot is located on.
How many participants are from these servers in total.
And how many channels are there.

valid perch
#

It also needs awaiting

tough lance
spiral frigate
#

Code

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


        # main

        servs = bot.guilds
        users = bot.users
        channels = bot.channels

        print(servs)

error

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 96, in стат
    servs = bot.guilds
AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
#

this file if that cog

elfin island
#

you used commands.bot somewhere where you were supposed to use commands.Bot (capital B)

spiral frigate
#

Everything is exactly a mistake

placid skiff
#

There is a way to save errors from the console into a file?

spiral frigate
#

Type upload here as a file and or type of logs

#

if there are logs then I do not know how it is done

#
import discord
from discord.ext import commands
import datetime as DT

from discord.ext.commands import Bot



class Info(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
#-----------стат----------#

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


        # main

        servs = Bot.guilds
        users = Bot.users
        channels = Bot.channels

        print(servs)


#-------------------------#

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

Don't name your functions with Russian letters

#

And it's self.bot. instead of Bot.

spiral frigate
#

In fact, I can use them and I have no problems

slate swan
#

However, you should not.

boreal ravine
slate swan
boreal ravine
#

he knew but he still posted the error

gloomy coral
#

HOW DO I ADD A COOLDOWN

reef shell
unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
gloomy coral
reef shell
twilit scarab
#

Guys, how to indent in a embed?

#

If im using these invisible characters it will work for PC but on mobile it will output little boxes with "?" inside

#

Code is

embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value='᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼᲼@everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)
wanton cipher
#

How can I check if any occurrence in a list appears in another? (I am trying to see if a list of user ids are in another list of user ids)

willow pulsar
#

Is this what you meant

wanton cipher
#

I think I might have found I solution, but I'll test yours

#

(my solution)

list1 = [...]
list2 = [...]
if any(list1) in list2:
  ...
slate swan
#

!d

rigid torrent
#

!d

#

!d python

willow pulsar
wanton cipher
willow pulsar
#

any return true if all values in the list are True(none empty string, numbers other than 0 etc)

wanton cipher
#

ah

wanton cipher
willow pulsar
#

I might have made a mistake when i said any return true if all values in a list are it
Thats wrong
It returns true if any values in the list are true

#

Sorry about that

wanton cipher
slate swan
#

Can anyone help me in using motar for mongo db database

reef shell
#

It's motor

#

For database related questions you may use #databases

slate swan
#

Not related to Discord bots

#

But looks like the Hocus Pocus theme

#

in file : ['hello', 'hi', 'bye']

with open(f'{path}/text.txt', encoding='utf-8') as f:
    lst = f.read().splitlines()
print(lst)
lst.remove('hello')
print(lst)

result : ['hi', 'bye']
But it is not deleted inside the text file.

boreal ravine
slate swan
#

okay

gloomy coral
gloomy coral
reef shell
gloomy coral
boreal ravine
#

slash commands still work with cooldown iirc

gloomy coral
#

i did @gilded grove_ext.cooldown

boreal ravine
#

no shit sherlock you're supposed to do commands.cooldown()

boreal ravine
gloomy coral
#

no

#

oh ok

steep estuary
#

how i can wait for multiple message at a time ?

#

i want to take all message in time

slate swan
#

Is it possible to let my bot change its nick name in a server every 5 Minutes or 20?

steep estuary
#

use loop

slate swan
#

k

steep estuary
#

task*

gloomy coral
#

just say(repeat after me)

#

Ole ole, I'm a guacamole

slate swan
#

huh

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
valid niche
#

that's because it's no concrete item like a class or method, instead it's just a primer on the ext in general

slate swan
#

#EndGoLang

#

Good we don't think about the same language bravemmlol

gloomy coral
#

welp tht doesnt work

#
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py:415> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn options.1: Option name option is already used in these options')>
Traceback (most recent call last):
  File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 491, in sync_all_commands
    raise ex
  File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 471, in sync_all_commands
    existing_cmds = await self.req.put_slash_commands(
  File "C:\Users\jason\chad\venv\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Option name option is already used in these options
#

Error?

slate swan
#

Heyyy, can someoen help me with creating task? I need to start a looping task by command

#

How can i start a task using a command?

twilit scarab
#

how to display the amount of deleted messages with this code?

@client.command(name='löschen', pass_context=True)
async def löschen(ctx, limit:int):
    await ctx.channel.purge(limit=limit)
    await ctx.send('Es wurden {limit} Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)
slate swan
#

So get the length of that list

#

Such as

x = await ....
len(x)
boreal ravine
#

pugre

slate swan
#

And you shouldn't put ö in the function name

#

Do like oe

boreal ravine
#

it's his language that he's using though

slate swan
twilit scarab
#

So it is not possible to display it in this line

 
await ctx.send('Es wurden {limit} Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)
``` with the given information without adding more code?
slate swan
#

But in German you often write oe instead of ö ;)

twilit scarab
#

thanks to you both

boreal ravine
#

use an api

slate swan
slate swan
#

Using requests

boreal ravine
slate swan
#

aiohttp also does web requests Pepega

#

Wasn't saying the requests library facepalm

boreal ravine
#

or requests

boreal ravine
#

ok

unkempt canyonBOT
#

class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
slate swan
#

At this point it's Python knowledge

#

Who doesn't

boreal ravine
#

indexing dictionaries like what any other normal python user would do

#

try it and see

twilit scarab
#
@client.command(name='löschen', pass_context=True)
async def löschen(ctx, limit:int):
    await ctx.channel.purge(limit=limit)
    await ctx.send('Es wurden',len(int), 'Nachrichten gelöscht! :white_check_mark: '.format(ctx.author), delete_after=5)

Forgive me if im not seeing the apparently, im a complete freshie 🙈

I did it with len, but it somehow gives me a TypeError: object of 'type' has no len()

#

Whats my mistake in here

#

the ö = oe I'll change later on 👀

thin valley
#

because "int" is also a variable type

#

Integer

boreal ravine
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

thin valley
#

Soll ichs dir auf deutsch sagen? @twilit scarab

boreal ravine
#

bru

twilit scarab
twilit scarab
thin valley
#

Du musst schreiben: "es wurden" + limit + "Nachrichten geloescht."

#

Falls limit die Zahl der geloeschten Nachrichten ist.

boreal ravine
#

or do what luna said

twilit scarab
#

Okay ich werd das eben versuchen. Ja Limit ist die Zahl der gelöschten Nachrichten. Ich bin grad so happy das hier jemand unterwegs ist der Deutsch kann. 😄 Ist schwierig guten support ausserhalb der englischen community zu bekommen

thin valley
#

I told him to just write: limit + "messages were deleted". Because limit is the number of deleted messages @boreal ravine

thin valley
twilit scarab
twilit scarab
thin valley
#

That's true, I'm not here to replace anyone or kick anyone of their spot.

boreal ravine
#

👍

thin valley
#
@client.command()
async def emoivb(ctx, channel: discord.TextChannel, *, new_name):
    await channel.edit(name=new_name)
``` This should work. It edits the name of a Textchannel, but you can change that yourself too.
#

This is by channel-name.

twilit scarab
boreal ravine
#

🗿

slate swan
#

!rule 4

unkempt canyonBOT
#

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

slate swan
#

@thin valley@twilit scarab^

thin valley
#

Ouh

boreal ravine
#

get the channel object using bot.get_channel() or guild.get_channel() and then edit it

thin valley
#

I'm sorry, we will take this to our DM's

#

Sorry guys!

slate swan
#

No problemo

pine lava
#

how do i get a user avatar url in v2.0?

manic wing
#

I dont use 2.0 rip

pine lava
#

oh

manic wing
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
manic wing
#

just run a dir on that

pine lava
#

k

slate swan
#

What is that

#

Create a task loop

boreal ravine
#

your using a decorator

#

without a function

#

why

#

also this is gonna be invalid syntax and Ids are ints not strings

boreal ravine
#

example of tasks.loop:

@tasks.loop(seconds=5) #loops every 5 seconds iic
async def your_function_name():
  #code

your_function_name.start()
#

who told u that? and it isnt

#

this isnt

upbeat otter
#
@client.command()
async def poll(ctx, *, text):
  if not (ctx.message.author.guild_permissions.view_server_insights):
    await ctx.reply("You do not have the permission to set up a poll")
    return
  options = text.split("|") 
  print(options)
  embed = discord.Embed(title="Poll by a Member", description=f'''1. {options[0]}
2. {options[1]}''',color=ctx.message.author.color) 
  try:
    with open("configure.json", "r") as f:
      data = json.load(f)
    channelToSend = data[str(ctx.guild.id)]["poll"]
    channel = client.get_channel(channelToSend)
    print(channel)
    message = await channel.send(content=None, embed=embed)
    await message.add_reaction("🅰")
    await message.add_reaction("🅱️")
  except Exception as e:
    print(e)
    await ctx.send("Please configure a poll channel first!")

why is this not working 🥲

slate swan
#

IDs are integers, not strings

boreal ravine
#

i said that before i dont know if he saw it though

#

https://discordpy.readthedocs.io/en/stable/migrating.html
Before v1.0, all snowflakes (the id attribute) were strings. This has been changed to int.

Quick example:

# before
ch = client.get_channel('84319995256905728')
if message.author.id == '80528701850124288':
    ...

# after
ch = client.get_channel(84319995256905728)
if message.author.id == 80528701850124288:
    ...
finite plinth
#

yo guys for whatever reason when i run my bot i get this error

#

does anyone know why?

boreal ravine
#

yes

#

u can only change a channel name every 5 minutes tho (rate limit)

upbeat otter
#

guys, my code isnt working like this

if not (ctx.message.author.guild_permissions.view_server_insights):
    await ctx.reply("You do not have the permission to set up a poll")
  else:
    options = text.split("|") 
    print(options)
#

well...copy paste the ID again

#

happens with me too

#

oof, try again

slate swan
#

The channel is not in cache

upbeat otter
#

ohh

slate swan
#

Use get_channel and if it returns None, use fetch_channel

boreal ravine
#

wait before start thing

#

hm

#

bot.fetch_channel()

slate swan
#

No

#

A simple one-line solution would be x = bot.get_channel(id) or await bot.fetch_channel(id)

eager pawn
#

mhm

boreal ravine
#

thats what i was saying though

slate swan
#

No

boreal ravine
#

we dont need to write everything

slate swan
#

The way you said it was to replace it

boreal ravine
#

yeah

eager pawn
slate swan
#

Which is bad

#

So no, don't do it.

pine lava
#

how do i get the creation date of a guild?

slate swan
#

You shouldn't always make API calls, only if it's not in cache

boreal ravine
unkempt canyonBOT
slate swan
#

As I said

#

Don't do what kayle said

#

It's bad practice

boreal ravine
#

what did you do

#
x = await bot.fetch_channel()
await x.edit()
``` its not that hard
slate swan
#

Don't. Always. Use. API. Calls.

#

Only use them if it's not in cache

eager pawn
#
x = await bot.fetch_channel(id goes here)
await x.edit(name="whatever")```
slate swan
eager pawn
#

yes.

slate swan
#

Only use them if it's not in cache

eager pawn
#

my bad.

boreal ravine
eager pawn
#

get_channel is more reliable

boreal ravine
slate swan
#

I literally send

eager pawn
#

editing a channel isnt that hard cmon

slate swan
#

A one line solution

#

Is it that hard to read?

boreal ravine
#

it isn't

#

i was asking how would you know when

#

to make API calls?

eager pawn
#

my lord.

slate swan
boreal ravine
#

how would you know if it wasnt cached or not

slate swan
#

No.

#

Anyways, I give up

boreal ravine
slate swan
#

You do you

boreal ravine
#

🤷‍♂️

slate swan
slate swan
#

Only thing I edited was

  • channel => bot (typo)
  • client => bot (typo)
  • added x =
boreal ravine
eager pawn
#

hey uh whats everyone's ig, greatest bot they've made?

slate swan
#

A bot that answers questions for me

eager pawn
#

amazing.

pliant gulch
eager pawn
#

..

slate swan
eager pawn
#

thats great

#

using aiohttp?

slate swan
#

Nah asyncpraw

eager pawn
#

or..

#

oh i completely forgot praw exists

#

lmao

slate swan
#

Yeah lmao

coral vessel
#

How to make this multiple? for example
in the picture if someone say "Ping" bot will say "pong"
so i want add new different command with different answer from bot, how to that?

boreal ravine
gloomy spindle
#

guys how to fix this one

#

how to fix his one

#

how to fix this one

eager pawn
final iron
eager pawn
#

indentation wtf

final iron
#

Also you leaked your token

eager pawn
#

might wanna regenerate that

coral vessel
#

i always get this every time CTRL + C, but my code run well

Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000026D0E59C550>
Traceback (most recent call last):
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\Indra Constantine\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

is this okay?
i just learning python 3 days ago

brave vessel
slate swan
slate swan
#

@gloomy spindle Spamming is not needed, just as side note

#

You won't get more attention

slate swan
#

Ill give you less for being annoying

#

^

boreal ravine
#

how would I remove this from the default help command

slate swan
odd pendant
#

well that would remove it overall, idk if you can remove it from the default help command without making a custom one

boreal ravine
#

hm

slate swan
#

Why use the default help command and not a custom one?

odd pendant
#

if you make a custom help command, you can just use something like ```py
for cog, _cmds in mapping.items():
filtered_commands = await self.filter_commands(_cmds, sort=True)

if [c.name for c in filtered_commands][0] != "help":
    # you could append all commands to a list or something, ignoring the help command```
twilit scarab
#
platz = ""
  for i in range(0, 100):
    platz += "\n"
  embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value=f'{platz} @everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)

Hello i wanna indent my embed. So that it looks like the bottom. (l.a Image)
I just played around with the range but no effect shows up. Can you maybe help me out?

odd pendant
#

well \n wouldn't add whitespace, it would create a new line

#

and i'm not sure if theres a set way to go about adding whitespace

slate swan
odd pendant
#

he doesn't want new lines

twilit scarab
#

new line

Would be great anyway. I just want that the start isn't connected to the 🚙 Fahrzeuge 🚙 . A new line would do it's job.

On the screen its done with 103x \u200b 🤡 😂

sage otter
slate swan
slate swan
sage otter
twilit scarab
#
embed.add_field(name=':blue_car: **__Fahrzeuge__** :blue_car:', value=f'\n @everyone die Abstimmung bezüglich der Fahrzeuge war eindeutig. Deshalb haben wir nun die Fahrzeuge angepasst und erhöht. Ab sofort findet ihr vollständige Autos und in größerer Menge. Gleichzeitig wurden die [#892752383107559444](/guild/267624335836053506/channel/892752383107559444/) angepasst. Also lest euch diese nun bitte erneut durch. Auf Altar wird es ab sofort auch keinen An- oder Verkauf mehr von Fahrzeugen geben.', inline=True)

Tried this too, didn't work :/

Just pressing space won't work. Adding invisible characters work for PC Output. On Mobile Phones you'll see white boxes filled with "?" so that's no option too

slate swan
cloud dawn
steady flume
#

how to make it so that if a member has such a status, the bot will show an emoji of this status ???

slate swan
cloud dawn
steady flume
#

yes

slate swan
#

!d discord.Member.status

unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
slate swan
#

Use this

steady flume
#

whats enums ?

cloud dawn
#

Do enums also contain the emoji?

slate swan
#

It just returns one of the status enum

slate swan
kindred epoch
#

Well, you need to add the emoji urself

slate swan
#

^

#

!d discord.Status

unkempt canyonBOT
#

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

It won't give you the emoji

slate swan
#

It returns one of these

#

Your job to put emotes etc.

steady flume
kindred epoch
#

Check what the status is and then use if statements to set the emojis

steady flume
#

here bot, it sent Status with this emoji

#

i can add the same emoji, but how?

kindred epoch
#

DND will return dnd, Online will return online, Offline will return offline and Idle will return idle

steady flume
#

thank you!

kindred epoch
#

So

if discord.Status == "dnd":
    #do something 
steady flume
#

ohhhhh, thank you!

#

imma eat and in few mins ill try ur way

#

thank you very much

slate swan
#

or just check with discord.Status.dnd

kindred epoch
#

Ye

slate swan
#

Does the same, your choice what you choose and prefer to use

#

I personally love to work with enums

boreal ravine
rotund nova
#

Can i give alias for client.command

boreal ravine
#

you can pass in a kwarg (aliases) in your bot decorator the values must be a list or a tuple though

rotund nova
#

you give me e.g?

#

client.command(name='command')
??

slate swan
cloud dawn
slate swan
manic wing
#

are you getting help or giving help

#

i cant tel

slate swan
#

my bad

#

😔 am kinda high

rotund nova
#

thanks*

covert palm
#

any js dev here, i need a bit of help, its pretty easy question i think

manic wing
#

python server.

slate swan
#

JavaScript channel there

safe fulcrum
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

how do I make a fight command? example:
user:!fight @x
bot: @y has started a fight with @x
bot: what to do? @y fight or block or kick

#

these are codes

@bot.event
async def on_message(message):
    if message.content.startswith('!test'):
        channel = message.channel
        await channel.send('hm')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await bot.wait_for('message', check=check)
        await channel.send(f'ok{msg.author.mention}')```
#

i am using on_message(message) so the user can reply with prefix
no !fight kick or !kick just kick till the fight is over

rain ridge
#

how do you edit contents of a embed?

cloud dawn
rain ridge
#

🤔

brazen raft
#

You copy, change stuff, and edit the message by reassigning the embed argument.

rain ridge
#

so u cant just use message.edit

brazen raft
#

You can.

rain ridge
#

how tho?

#

ik message.edit works on simple msgs

brazen raft
#

Pseudo code:

e = discord.Embed() # whatever embed you make, k?
msg = await discord.Messageable.send(embed=e)
e.title = "new title"
await msg.edit(embed=e)
rain ridge
#

lemme test

brazen raft
#

and discord.Messageable will be either ctx, a channel, or any object which inherits send from discord.Messageable

rain ridge
#

i'll send the piece of code

brazen raft
#

Keep in mind that there is a total of five edits in a total of five seconds cooldown.

unkempt canyonBOT
#

Hey @rain ridge!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

rain ridge
#
except:
            convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
            time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]
        if time > 86400:
            await ctx.send("I can\'t do timers over a day long")
            return
        if time <= 0:
            await ctx.send("Timers don\'t go into negatives :/")
            return
        if time >= 3600:
            message = embed=discord.Embed(title="Timer")
            embed.add_field(name="undefined", value=f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds", inline=False)
            await ctx.send(embed=embed)
        elif time >= 60:
            message = message = embed=discord.Embed(title="Timer")
            embed.add_field(name="undefined", value=f"Timer: {time%3600//60} minutes {time%60} seconds", inline=False)
            await ctx.send(embed=embed)
        elif time < 60:
            message = message = message = embed=discord.Embed(title="Timer")
            embed.add_field(name="undefined", value=f"Timer: {time%60} seconds", inline=False)
            await ctx.send(embed=embed)
        while True:
            try:
                await asyncio.sleep(5)
                time -= 5
                if time >= 3600:
                    await message.edit(value=f"Timer: {time//3600} hours {time %3600//60} minutes {time%60} seconds")
                elif time >= 60:
                    await message.edit(value=f"Timer: {time//60} minutes {time%60} seconds")
                elif time < 60:
                    await message.edit(value=f"Timer: {time} seconds")
                if time <= 0:
                    await message.edit(value="Ended!")
                    await ctx.send(f"{ctx.author.mention} Your Timer Has ended!")
                    break
            except:
                break
    except:
        await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**....")
#

there are some try: statements too

slate swan
rain ridge
#

idk how it works

brazen raft
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

spiral frigate
#

How can I get how many channels there are on the servers where there are total

rain ridge
#

uhh

unkempt canyonBOT
slate swan
#

Get the length of that, as it returns a list

cloud dawn
slate swan
#

Yes?

#

Just put ignore them, not that complicated

spiral frigate
#

on the servers where the bot is located.
Find out how many channels there are in total

brazen raft
#

@rain ridge I want to write a simple command so you can learn from it:

@bot.command()
async def hello(ctx: commands.Context) -> None:
    e = discord.Embed(title="Reply", description="Uh...")
    msg = await ctx.send(embed=e)
    e.add_field(name="\u200b", value="Hi?")
    await asyncio.sleep(2)
    await msg.edit(embed=e)
cloud dawn
spiral frigate
#

So I don't even know how to get this one out.
My question is how to get and not how to translate to

cloud dawn
spiral frigate
#

Sorry for English I'm Russian

brazen raft
spiral frigate
#

That's what I know

surreal sierra
#

Hey, Im trying to create a way for the bot to send a msg at a specific clock time. I tried to do it with schedules but it didnt work. The bot just disconnects right after I start the script. is there any better way to do this or a way to fix it? I dont want to do it by using sleep I want somewhere to be able just type in a clock time for example 18:15 and the bot will send a msg everyday at that time.

brazen raft
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
spiral frigate
#

here they told me there that the current does not work

sum([len(guild.text_channels for guild in bot.guilds]) + sum([len(guild.voice_channels for guild in bot.guilds])
brazen raft
#

len(guild.text_channels) + len(guild.voice_channels)

spiral frigate
#

This is the output current of this server

brazen raft
#

You need from all of the servers combined?

spiral frigate
#

and I need all the servers where there is a bot

cloud dawn
#

len(guild.text_channels + guild.voice_channels)

cloud dawn
brazen raft
#
sum(len(guild.text_channels) + len(guild.voice_channels) for guild in bot.guilds)
spiral frigate
#
Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Baraban4ik\Desktop\Suzuki\cogs\info.py", line 97, in стат
    channels = sum(len(guild.text_channels) + len(guild.voice_channels) for guild in bot.guilds)
AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'
brazen raft
leaden jasper
#

How to get a channel

cloud dawn
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
spiral frigate
#

it works like this sum(len(guild.text_channels) + len(guild.voice_channels) for guild in self.bot.guilds)

leaden jasper
#
print(self.bot)
print(self.channel)
channelObj = self.bot.get_channel(self.channel)
print(channelObj)

<discord.ext.commands.bot.Bot object at 0x7f0fa3c0cdf0>
890646800019640380
None
None```

slate swan
#

how to can i get the channel id from the channel itself where i command my commands?

brazen raft
#

ctx.channel.id?

slate swan
#

aight

brazen raft
cloud dawn
#

He printed it.

brazen raft
#

I see.

leaden jasper
brazen raft
#

I wrote fetch not get

slate swan
boreal ravine
#

only in fetch_channel since it's a coroutine

brazen raft
manic wing
#

add invisible characters

boreal ravine
slate swan
#

manic wing
#

yeah

#

\u200b

spiral frigate
#

And how to find out how many commands a bot has

manic wing
shut axle
#

I literally installed python again and it shows me that...

manic wing
#

if linux, you need to install python-pip

shut axle
#

Windows.

brazen raft
slate swan
spiral frigate
#

Outputs the current so len(ctx.bot.commands).
but it also outputs the event for some reason

manic wing
#

for starters, does python or python3 do anyrhing. maybe you mean pip3 as well @shut axle

slate swan
#

using discord components,

@bot.command()
async def leaderboard(ctx):
  check = await lb_loaded()
  if check == False:
    await ctx.send("Leaderboard hasn't loaded yet, please try again in a few minutes")
    return
  starting = 0
  to = 20
  invis = '‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎'
  result = await get_positions(ctx.guild, starting, to)
  async def lb_embed(pos):
    embedVar = discord.Embed(title="Leaderboard:" + str(invis), color=ctx.author.color)
    embedVar.add_field(name="** **", value=str(pos), inline=False)
    embedVar.set_footer(text=f"guild: {ctx.guild}")
    return embedVar

  msg = await ctx.send(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])
  message = ctx.message
  interaction = await bot.wait_for("button_click", check = lambda inter: inter.message.id == message.id)
  if interaction.custom_id == "button_nex":
    starting = starting + 20
    to = to + 20
    result = await get_positions(ctx.guild, starting, to)
    await msg.edit(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])
  elif interaction.custom_id == "button_prev":
    starting = starting - 20
    to = to - 20
    result = await get_positions(ctx.guild, starting, to)
    await msg.edit(embed=await lb_embed(result), components=[Button(label='Previous', style=ButtonStyle.blue, custom_id='button_prev'), Button(label='Next', style=ButtonStyle.blue, custom_id='button_nex')])

getting the error "interaction failed"

#

anyone knows what's up?

manic wing
#

commands does not display events

manic wing
shut axle
#

When I am trying to check the version of python it shows me that

#

even I already have python installed.

slate swan
spiral frigate
#

I don't know, I have 7 commands output, although there are 6 of them.
And events 1

stiff nexus
#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/cogs/owner.py", line 1284, in on_raw_message_edit
    if payload.author.id != self.bot.owner:
AttributeError: 'RawMessageUpdateEvent' object has no attribute 'author'
```help???
shut axle
#

I tried.

slate swan
#

Dang

#

@shut axle have you tried checking the environment variables

shut axle
#

?

stiff nexus
#
    @commands.Cog.listener()
    async def on_raw_message_edit(self, payload):
        if payload.author.id != self.bot.owner:
          return
        channel = self.bot.get_channel(payload.channel_id)
        try:
            message = await channel.fetch_message(payload.message_id)
        except:
            pass
        else:
            await self.bot.process_commands(message)
slate swan
# shut axle ?

Have you checked environment variables in your computer

brazen raft
#

@shut axle did you make sure the box saying "Add Python 3.x to PATH" is checked?

slate swan
#

If not well thats the problem

sick birch
brazen raft
#

@spiral frigate len(self.bot.commands) + len(self.bot.events)

shut axle
#

@brazen raft ?

brazen raft
#

That.

shut axle
#

Okayt

brazen raft
#

Good.

sick birch
#

How well does Python 3.10 work with d.py?

brazen raft
#

As well as it does with Python 3.9.

spiral frigate
sick birch
shut axle
#

f it doesn't work @brazen raft

sick birch
brazen raft
sick birch
#

If you have a custom implementation of the help command and it shows events alongside the commands, then your custom help command logic is most likely flawed

spiral frigate
sick birch
#

Is it showing the event as a command on Discord?

spiral frigate
#

And how to check it

sick birch
#

Well if you don’t know I assume it doesn’t

#

So it really isn’t an issue then

spiral frigate
#

Then why should I output 7 commands instead of 6

#

help

ocean leaf
#

i send this message but it gives EmojiNotFound error

#

here is my code

shut axle
#

The pip install discord.py shows this and not doing anything...

silk mauve
#

Guys, this is my footer and I want to add my discord profile next to my name, how to do that?

#

Like this

#

huh

dapper cobalt
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
dapper cobalt
#

Pass icon_url.

shut axle
ocean leaf
slate swan
silk mauve
#

Embed.set_footer(*, text="Zeatman • 26.10.2021, icon_url="https://images-ext-1.discordapp.net/external/cJBUV5cIOm0u_YlsUia0EW4MpIM05dHrdb0maocfo3o/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/371597683548225537/a_cc7d8579fb009c8f667ba781da9565c9.gif") await ctx.send(embed=embed)

slate swan
#

Small e

silk mauve
#

Its showing me an error

#

Still error

slate swan
#

Without *,

silk mauve
#

let me run

slate swan
#

E should be small and remove *,

#

Don't copy paste the docs of the function xD

silk mauve
#

I have already done that

#

but

#

Now I have added this "

#

And the other link is not green

#

idk how to say that

#

I got it lol

void dew
#

What is this

#

And now this

cloud dawn
#

!indention

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

void dew
#

What does this mean and what to do

slate swan
void dew
silk mauve
slate swan
#

cool

cloud dawn
#

line 3000 😳

void dew
spiral frigate
#

how to find out when the bot was launched

cloud dawn
#

I suggest showing line 3117

cloud dawn
#

!d datetime.datetime.now

unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
#

This package provides a DateTime data type, as known from Zope. Unless you need to communicate with Zope APIs, you're probably better off using Python's built-in datetime module.

cloud dawn
#

Ignore this package

spiral frigate
#

I still didn't understand you

#

How will I get the info there when the bot was launched

dapper cobalt
unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
slate swan
#

add a datetime.datetime.now() variable before bot.run() and return it whenever you want the time of bot's launch

spiral frigate
dapper cobalt
#

I think he wants to just know when the bot is on. Not "when" as in time, but upon its launching.

dapper cobalt
spiral frigate
#

Type so that the variable outputs: That the bot was launched on October 21...

#

sorry for my english I use a translator

spiral frigate
outer violet
#

How do I make my bot stop adding channels? Cuz it’s just making a new channel until it reaches the limit and idk why


import discord
from discord.ext import commands


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

    @commands.Cog.listener()
    async def on_message(self, message):
        empty_array = []
        guild = self.client.get_guild(900458404953333808)
        channels = await guild.fetch_channels()
        channel = discord.utils.get(channels, name=str(message.author.name))

        if channel is None:
            category = discord.utils.get(guild.categories, name="Tickets")
            channel = await guild.create_text_channel((message.author.name), category=category)

        if message.author == self.client.user:
            return
        if str(message.channel.type) == "private":
            if message.attachments != empty_array:
                files = message.attachments
                await channel.send("[" + message.author.display_name + "]")

                for file in files:
                    await channel.send(file.url)
            else:
                await channel.send("[" + message.author.display_name + "] " + message.content)

        user = await message.guild.fetch_member(str(message.channel.name))
        if message.attachments != empty_array:
            files = message.attachments
            await user.send("[" + message.author.display_name + "]")

            for file in files:
                await user.send(file.url)
            else:
                await user.send("[" + message.author.display_name + "]" + message.content)

def setup(client):
    client.add_cog(test(client))
outer violet
#

Where do I put that?

#

@slate swan

slate swan
#

After creating your channel duh

outer violet
#

Oh

spiral frigate
#

How to output the bot launch date

#

please

slate swan
#

Save the timestamp/date in a bot variable when starting it

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
# outer violet Oh

After it makes the channel just use else:break or just add break at the bottom of the function

rain ridge
#

this doesnt seem to edit the embed what am i doing wrong?

        if time > 86400:
            await ctx.send("I can\'t do timers over a day long")
            return
        if time <= 0:
            await ctx.send("Timers don\'t go into negatives :/")
            return
        if time >= 3600:
            message = discord.Embed(title="Timer")
            message.add_field(name="Bot",value=f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds", inline=False)
            await ctx.send(embed=message)
        elif time >= 60:
            message=discord.Embed(title="Timer")
            message.add_field(name="Bot",value=f"Timer: {time%3600//60} minutes {time%60} seconds", inline=False)
            await ctx.send(embed=message)
        elif time < 60:
            message=discord.Embed(title="Timer")
            message.add_field(name="Bot",value=f"Timer: {time%60} seconds", inline=False)
            await ctx.send(embed=message)
        while True:
            try:
                await asyncio.sleep(5)
                time -= 5
                if time >= 3600:
                    message.add_field(value=f"{time//3600} hours {time %3600//60} minutes {time%60} seconds")
                    await message.edit(embed=message) 
                elif time >= 60:
                    message.add_field(value=f"{time//60} minutes {time%60} seconds")
                    await message.edit(embed=message) 
                elif time < 60:
                    message.add_field(value=f"{time} seconds")
                    await message.edit(embed=message) 
                    
                if time <= 0:
                    await message.edit(title="Ended!")
                    await ctx.send(f"{ctx.author.mention} Your Timer Has ended!")
                    break
            except:
                break
    except:
        await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**...." 
spiral frigate
slate swan
spiral frigate
#

exactly the time

slate swan
#

Nvm

#

Dont use else

surreal sierra
#

I made a command to ping you at the exact same time you tell the bot to ping you at, but how do I add a way so the bot will ping me at that exact same time everyday instead of just once?

This is what I got now

@bot.command()
async def p(ctx, chour=None, cminut=None):
    if chour is None:
        await ctx.send("You must give hour and minute in a 24 hour clock time")
    elif cminut is None:
        await ctx.send("You must give hour and minute in a 24 hour clock time")
    else:
        async def func():
            channel = bot.get_channel(channel_id)
            await channel.send(f"{ctx.message.author.mention}")

        scheduler = AsyncIOScheduler()
        scheduler.add_job(func, CronTrigger(hour=chour, minute=cminut, second="0"))
        scheduler.start()
        await ctx.send(f"Wew bot will remind {chour}:{cminut}")
rain ridge
slate swan
#

Because you need to provide a new embed object when editing your message

#

Just like when sending

rain ridge
#

so it means i can add something else but can't remove existing one?

slate swan
#

And edit only works on a message, not on an embed

#
mess = await ctx.send(...)
await mess.edit(...)
rain ridge
#

i'll see bout it

velvet crest
#

How can i disable commands per server wise ? I wanted to know what all info i should store on the db (aprt from guild id and stuff) and check the commands are disabled or not ? Would appriciate if any one could give me the ideology behind it

spiral frigate
#

I need to pass date_start = datetime.now() to another py file

#

Pass it to cog

slate swan
#

No

slate swan
silk mauve
#

import time, requests, nekos, sys, os, config
ModuleNotFoundError: No module named 'nekos'

Process finished with exit code 1

#

import time, requests, nekos, sys, os, config

spiral frigate
#

so I have 2 files bot.py and info.py
info.py - cog
And there I use this variable.

weary onyx
#

i need help

#

how do i send a message using a function

leaden jasper
#

where is the ratelimit list

leaden jasper
slate swan
#

How can I make the bot speak when a message is sent to the channel,
and then delete the past bot message and send a new one when the message is sent again?
The image is like fixing the bot's message at the bottom.

#

@spiral frigate For the 5th time

#

Use. Bot. Variables.

weary onyx
weary onyx
#

so

silk mauve
#

i got it

weary onyx
#

it tells me i need a arg so

spiral frigate
weary onyx
#

i just put None?

slate swan
weary onyx
#

'NoneType' object has no attribute 'send'

slate swan
#

Since your function asks for a ctx parameter

weary onyx
#

im new to python i used to use golang

slate swan
#

Give a ctx parameter

weary onyx
#

ok

slate swan
#

That has nothing to do with the language switch

#

That's the same in all languages

weary onyx
#

ik

slate swan
#

That won't do what they want

weary onyx
#

NoneType' object has no attribute 'send'

slate swan
#

They want to disable the command per server, and not for every server

#

So adding dm_only will just block everything

leaden jasper
#

They have to use a database to store guild ids and check if ctx is in it

#

its a long process

slate swan
#

Not if ctx is in it

#

But yes something like that

leaden jasper
#

where can I find the ratelimit list?

slate swan
#

Use a database, store the command name and guild id, and store a boolean

outer violet
slate swan
#

Use return instead of break

velvet tinsel
#

can you tell when someone is spamming by using a bot? like

@client.listen()
async def on_spam(ctx):
  if ctx.author.sendMessage < 0.1 seconds:
  await ctx.send("stop spamming!")

or something like that?

slate swan
slate swan
velvet tinsel
#

thats pseudo

leaden jasper
unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
slate swan
#

No that won't help (again)

#

Stop giving false help

leaden jasper
#

how wont that help

slate swan
#

That's command cooldown afacepalm

#

Read the entire question instead of just a few words

velvet tinsel
slate swan
slate swan
#

It won't help you at all

#

Hes trying to check if someone is spamming

velvet tinsel
#

ok

#

so like if someone started spamming hi hi hi hi hi hi it would say like stop spamming!

leaden jasper
# velvet tinsel so how would it work?
import discord
from discord.ext import commands

import datetime
import time

b = commands.Bot(command_prefix='not a bot')
b.remove_command("help")

time_window_milliseconds = 5000
max_msg_per_window = 5
author_msg_times = {}
# Struct:
# {
#    "<author_id>": ["<msg_time", "<msg_time>", ...],
#    "<author_id>": ["<msg_time"],
# }


@b.event
async def on_ready():
    print('Bot is Ready')


@b.event
async def on_message(ctx):
    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:
        await ctx.send("Stop Spamming")

b.run('stack overflow')
slate swan
#

Never did that but I guess you'd need to save the message author and when the message got send, then compare the new message sent time with the old message sent time

slate swan
#

You're not helping anyone

#

Move on to another server

leaden jasper
#

well I need help too

harsh cradle
#
@bot.command()
@commands.has_role('- Hi Owners')
async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
        if member == None:
            return
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(member)

        user_id, guild_id, xp, level = result
        print(xp, level)

        level = lvl
        xp = 0

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed to {lvl}")
``` i have givelevel command and its work fine but how to move it and make it work without cog
velvet tinsel
#

then how

#

do I do anti spam?

slate swan
leaden jasper
#

its nowhere on google

slate swan
#

I wouldn't use a db

velvet tinsel
slate swan
#

Simply a dict is enough

slate swan
slate swan
leaden jasper
velvet tinsel
#

ok

slate swan
#

Spoonfeeding is irrelevant

#

And you don't even understand the code by yourself

slate swan
#

So don't do copy paste code from internet and think you're helping someone thanks

leaden jasper
#

its just if statements and dicts

slate swan
#

Then you can understand any game's code I guess

leaden jasper
#

hm really

slate swan
#

Simply some functions, loops, if statements and else statements

#

Now code a game please

leaden jasper
#

I dont know what this means

slate swan
#

You don't know yourself what the code does, so copy pasting is irrelevant

#

Just move on to another server if you want to send your copy pasted code

leaden jasper
#

me? I know what it does

slate swan
leaden jasper
#

they just want an answer

#

so give them one asap

slate swan
#

Well you're not answering

#

You're spoonfeeding

#

Which is not the same

slate swan
leaden jasper
#

well the code just uses if statements and dicts they can understand that on their own

#

they just wanted the logic

slate swan
#

Let's just take popcorns and wait @slate swan

leaden jasper
#

well i dont speak for them so ask them to see what they say to prove i'm wrong

slate swan
#

How do I log images? If my bot posts the image link to a logging channel and then deletes it then the link becomes invalid

#

Well that's how Discord works

#

Yeah

#

When you delete the message the content is invalid

leaden jasper
#

Download the file and then send it

slate swan
#

When you delete the image the image uploaded to Discord gets removed from their CDN

#

yeah I understand but is there any way for me to log it? Maybe like saving it locally then uploading?

#

If yes how?

slate swan
#

So you can try to download the picture and hope it's not removed yet from their CDN

leaden jasper
#

wait I need to check

slate swan
velvet tinsel
#

@slate swan you're right, I shouldn't be spoonfed. I'll try to figure out on my own

slate swan
slate swan
#

Never really did it but should work fine

#

@slate swan what does cdn mean?is it like their logging server

#

For content

boreal ravine
#

custom discord network idk

slate swan
#

No, it's where attachments, files, etc. are sent and saved basically

boreal ravine
#

saved yes

slate swan
#

Content Delivery Network

slate swan
#

Most of the services have a CDN nowadays

#

Ok

leaden jasper
slate swan
leaden jasper
#

then when u wanna send it use this

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
rugged delta
#

does self.bot.get_emoji(id) calls the API

slate swan
leaden jasper
#

dont work

dapper cobalt
#

!d discord.ext.commands.Bot.get_emoji

unkempt canyonBOT
slate swan
#

get_ never does if I remember correctly

#

Only fetch_ does

slate swan
rugged delta
#

yeah right ! , thanks

slate swan
#

No problemo

slate swan
# slate swan No problemo

Whats the difference of fetch and get does get searches for name or id of something and fetch will find it in discord?

#

fetch_ makes an API call to Discord, and get_ gets from the bot's cache

slate swan
#

Should use get_ and if it returns None, then use fetch_

#

Not recommend to always call the API

slate swan
#

Yep

#

And it's just a few word more

#

Cuz of api abuse

#
x = get_ or fetch_
#

So yeah, worth it

#

It will get first right

#

Will try get, then fetch if it returned none

slate swan
#

No problemo :p

velvet tinsel
#

is there a way to DM a user?

slate swan
#

!d discord.Member.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

oh yeah, I forgot 😅 thanks!

slate swan
#

@velvet tinsel search the api reference you can find all the commands

weary onyx
#

how can i send a message without a command

#

like using a function that has send in it

#

how do i run this def print_time(self, ctx: commands.Context, threadName): for z in split[int(threadName)]: if exitFlag: threadName.exit() try: ip = z server = MinecraftServer(ip, 25565) status = server.status() except: print("Invalid") else: print("Valid") channel = client.get_channel(902463513119842354) client.loop.create_task(channel.send("Found server: " + ip + " " + status.version.name + " " + str(status.players.online)))

spiral frigate
#

how to get a user ID from this format <@&ID> py

slate swan
#

Hey my snipe command takes these args

    async def snipe(self, ctx, *, channel: discord.TextChannel = None):

My snipe command is working perfectly so as to for a user to use ??snipe and ??snipe #channel however they can also use ??snipe <user_id> to show deleted messages from that user for someone reason any idea why?

random sleet
#

does someone know whats wrong here?

slate swan
slate swan
# random sleet

When you invoked the command you didn't specify which member

#

You have to do command member not just command

random sleet
slate swan
#

Then why add member as a required parameter

#

Remove it and instead of member use ctx.author.mention

#

I was about to say that lmao

random sleet
slate swan
#

Yw

slate swan
weary onyx
#

how can i send messages without a command so if i call another func

#

how do i call another func that sends a message

slate swan
#

Make the func take ctx or a message param and then send to the channel

slate swan
#

¯\_(ツ)_/¯

weary onyx
slate swan
#

No idea why

slate swan
slate swan
weary onyx
#

ye then how do i call it using asyncio.run because it just gives me error

velvet tinsel
#

I have a problem with the anti spam detector + muting...

@client.event
async def on_message(ctx, message):
    guild = ctx.guild
    counter = 0
    with open("spam_detect.txt", "r+") as file:
        for lines in file:
            if lines.strip("\n") == str(message.author.id):
                counter += 1

        file.writelines(f"{str(message.author.id)}\n")
        if counter > 5:
            # tells them to stop... and mutes them.
            mutedRole = discord.utils.get(guild.roles, name="Muted")
            # mutes them.
            if not mutedRole:
                mutedRole = await guild.create_role(name="Muted")
            spam_msg = discord.Embed(title="Stop spamming!", description=f"because you were spamming, you were temporarily muted for 10 seconds from {guild}")
            await message.author.send(spam_msg)
            # waits 10 seconds until they are unmuted.
            await asyncio.sleep(10)
            mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")

            await message.author.id.remove_roles(mutedRole)
            await message.author.id(f" you have unmutedd from: - {ctx.guild.name}")

then, if I keep spamming 'e', it returns with Traceback (most recent call last): File "C:[______________________________________]", line 343, in _run_event await coro(*args, **kwargs) TypeError: on_message() missing 1 required positional argument: 'message'
how do I fix that? I also want to mute them.

slate swan
weary onyx
#

no

#

i dont wanna run it

slate swan
weary onyx
#

with that

slate swan
#

Then?

weary onyx
#

so how do i run it

slate swan
#

ImportError: cannot import name 'game' from 'discord'

#

Getting this error.

velvet tinsel
slate swan
#

Should I send the code?

velvet tinsel
slate swan
#

Ok.

slate swan
velvet tinsel
#

or else we don't know what you're talking about

slate swan
#
from discord.ext.commands import bot
from discord import game
from discord.ext import commands
import asyncio
import platform
import colorsys
import random
import time

bot = commands.Bot(command_prefix="=", case_insensitive=True)
# you don't need discord.Client()

# this is dming users with a certain role
@commands.has_permissions(administrator=True)
@bot.command()
async def announce(ctx, role: discord.Role, *, msg): # announces to the specified role
    global members
    members = [m for m in ctx.guild.members if role in m.roles]
    for m in members:
        try:
            await m.send(msg)
            await ctx.send(f":white_check_mark: Message sent to {m}")
        except:
            await ctx.send(f":x: No DM could be sent to {m}")
    await ctx.send("Done!")
@announce.error
# feel free to add another decorator here if you wish for it to send the same messages
# for the same exceptions: e.g. @userinfo.error
async def _announcement_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send(":x: Role couldn't be found!")
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send(f":x: {ctx.author.mention}, you don't have sufficient permissions.")
    else:
        await ctx.send(error)

client.run("no") ```
weary onyx
slate swan
slate swan
slate swan
velvet tinsel
#

there is no from discord import game

#

🤣

slate swan
#

It's Game not game

#

It's a class not a function

velvet tinsel
#

its Game

slate swan
velvet tinsel
spiral frigate
#
TypeError: 'property' object is not callable

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

Traceback (most recent call last):
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
    raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "property" failed for parameter "member".

Who knows how to solve

slate swan
#

😂

spiral frigate
#

code

    @commands.command()

    async def профиль (self, ctx, member: discord.Member):
        print(member.id)