#discord-bots

1 messages Β· Page 692 of 1

tawdry perch
#

there is not .value attribute (by the error)

snow flare
#

why do I get an error when I try to send an ephemeral message using await ctx.channel.send("message", ephemeral=True)?

tawdry perch
slate swan
#

fuck

#

wrong error

snow flare
solar pine
tawdry perch
tawdry perch
solar pine
#

It's all good, I'm a bit confused as well

solar pine
#

Can I use synch modules in discord bots?

slate swan
#

got 1 more will send when i find ir

tawdry perch
#

I think await message.channel.send(content=None, embed=embed) you don't need content=None

boreal ravine
slate swan
tawdry perch
solar pine
slate swan
tawdry perch
#

might be

slate swan
#

gotta find that later

#

what abt the other error

tawdry perch
#

no idea tbh

#

are you trying to make a request or smth?

copper gulch
#
@client.command()
async def report(ctx, user:discord.User, reason):
    db = sqlite3.connect("main.db")
    cursor = db.cursor()
    cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
    result = cursor.fetchone()
    channel = get(result)
    await channel.send(f"{user} has been reported for {reason}")
    db.commit()
    cursor.close()

error:

 raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'send'

I printed the variable result and it gave me this: ('850356901232771085',)
and this is the table:

#

this is sqlite3

slate swan
tawdry perch
boreal ravine
tawdry perch
slate swan
copper gulch
slate swan
#

might just be a performance error

copper gulch
boreal ravine
tawdry perch
plain shadow
#

maybe trying this?

copper gulch
boreal ravine
#

in the get method

#

!d discord.utils.get

unkempt canyonBOT
#

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

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

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

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

Examples

Basic usage...
plain shadow
boreal ravine
#

spoonfeeder GG

copper gulch
copper gulch
plain shadow
#

if it doesn't work just do .replace("('", "")

#

and .replace("')", "")

#

then convert to int

#

and it should work

tawdry perch
#

why do you need to replace the ('?

copper gulch
#
@client.command()
async def report(ctx, user:discord.User, reason):
    db = sqlite3.connect("main.db")
    cursor = db.cursor()
    cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
    result = cursor.fetchone()
    id = ctx.guild.text_channels(result)
    await id.send(f"{user} has been reported for {reason}")
    db.commit()
    cursor.close()

and Bruh me

boreal ravine
#

bruh.

plain shadow
#

lemme write you a full example with the replace

tawdry perch
#

don't spoonfeed...

boreal ravine
snow flare
#

Is there some kind of event that a bot can listen to messages that are sent as a reply to the bot's message?

sullen shoal
#

!d discord.Message.reference

plain shadow
#
@client.command()
async def report(ctx, user:discord.User, reason):
    db = sqlite3.connect("main.db")
    cursor = db.cursor()
    cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
    result = cursor.fetchone()
    res1 = result.replace("('", "")
    res2 = result.replace("')", "")
    channel = client.get_channel(int(res2))
    await channel.send(f"{user} has been reported for {reason}")
    db.commit()
    cursor.close()

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.

boreal ravine
tawdry perch
#

what?

boreal ravine
tawdry perch
#

sql injection risk

plain shadow
#

it should work with ('ID') too

boreal ravine
#

im not the one who asked for help

boreal ravine
tawdry perch
maiden fable
#

Uhhh what

plain shadow
maiden fable
#

U need to add a comma to make it a tuple

plain shadow
boreal ravine
tawdry perch
maiden fable
unkempt canyonBOT
#

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

<class 'tuple'>
maiden fable
#

U need to add a comma, as I said

plain shadow
copper gulch
tawdry perch
tawdry perch
# boreal ravine whats that?

result of quick google "SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database."

upbeat otter
maiden fable
boreal ravine
upbeat otter
plain shadow
#
@client.command()
async def report(ctx, user:discord.User, reason):
    db = sqlite3.connect("main.db")
    cursor = db.cursor()
    cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
    result = cursor.fetchone()
    result = ''.join(result)
    channel = client.get_channel(int(result))
    await channel.send(f"{user} has been reported for {reason}")
    db.commit()
    cursor.close()

boreal ravine
tawdry perch
#

It's a bit hard to explain, the simple rule is to never use f string in SQL

maiden fable
boreal ravine
maiden fable
#

U can use f strings for user IDs and stuff, but never use those for names or user inputs

tawdry perch
#

it's bad usage

astral cobalt
#

If I wanted to have a event that was timed but I could cancel any time I wanted how would I do that, would the best way is to have a global variable that is changed when I stop the event?

boreal ravine
#

hm

tawdry perch
#

You should use placeholders as they are the safe method, learning to use SQL in bad way (in this case f-string) is not good

tawdry perch
plain shadow
#

why didn't you try tho

tawdry perch
#

try what?

plain shadow
#

int(result[0])

velvet tinsel
#

What’s the error

tawdry perch
plain shadow
#

sorry i'm confused

#

who's trying to get help lol

tawdry perch
#

I was just trying to get the best method to get it working πŸ˜…

#

And I think I maybe caused a bit of confusion

plain shadow
#

i proposed my solution, your is better

tawdry perch
#

main thing is to get it working πŸ‘

plain shadow
#

yeah, and in the better way!

tawdry perch
#

πŸ˜„ .

plain shadow
#

@copper gulch was gettin help

#

lol we got confused

rose shale
#

hello, inside cog using cog.listener can we track the voice part like if bot is not playing audio or something like that?

plain shadow
#

cog.listener is the same thing as @bot.event

#

i don't know if yes or not, but i think thaty is not an api event.

rose shale
#

yeah but my music part is inside cog so..

plain shadow
#

you should you a while loop

rose shale
plain shadow
#

when you start play, create a var named is_playing idk and assign it True

#

when you stop, assign it False

#

while is_playing:

#

i did this for my bot

copper gulch
#

eyyy problem solved

plain shadow
#

nice!

rose shale
snow flare
#

How can I get all the message references from a certain message, if I have the message object of it?

plain shadow
#

what do you mean with references?

snow flare
slate swan
#

hey, how do i get the person that invited a member?

plain shadow
unkempt canyonBOT
#

class discord.MessageReference(*, message_id, channel_id, guild_id=None, fail_if_not_exists=True)```
Represents a reference to a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").

New in version 1.5.

Changed in version 1.6: This class can now be constructed by users.
plain shadow
#

@snow flare it should be what you are searching for

upbeat otter
slate swan
plain shadow
#

sounds difficult to do

snow flare
upbeat otter
boreal ravine
upbeat otter
slate swan
slate swan
upbeat otter
unkempt canyonBOT
plain shadow
#

!pypi securedb

unkempt canyonBOT
#

securedb is a fast and lightweight Python framework to easily interact with JSON-based encrypted databases.

plain shadow
#

UwU

boreal ravine
#

yo nice lib @plain shadow

plain shadow
plain shadow
#

omg already got 37 downloads

boreal ravine
#

hm

violet nacelle
#

Hey. How do I add emojis to guild?
I've figured out how to add an emoji existing in my pc (a jpeg file stored locally) to an guild but how do I add an emoji which is an url, without downloading it first?

boreal ravine
uncut ruin
#

i tried installing discord.py (py -3 -m pip install -U discord.py, straight from the docs) and it gives me a few warnings, but overall it doesn't throw errors, and then, when i try importing it (import discord), it's not resolved, and throws an error saying i dont have discord.py installed

unkempt canyonBOT
#

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

Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji") for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
pliant compass
#

I'm making commands from a JSON file. My file looks like this:json [ { "name": "hello", "output": "Hello!" }, { "name": "goodbye", "output": "Goodbye!" } ] I have figured out how to make new commands, but I don't know how to make multiple. Here is my code:```py

Get data

def getData():
with open("customCommands.json") as jsonFile:
data = json.load(jsonFile)
return data

data = getData()
for command in data:

@commands.command()
async def newCommand(ctx):# Somehow change newCommand to command["name"]
    await ctx.reply(command["output"])
client.add_command(newCommand)

print(f"Added " + command["name"])
boreal ravine
uncut ruin
pliant compass
uncut ruin
#

yo wait

#

it works now...?

boreal ravine
#

lmao

uncut ruin
#

i ran the same command 5 times and it didnt work, but waiting 10 minutes now it works, i didnt even run it agian or anything

slate swan
#
@bot.command(help = "Shows the Guild the bot is in")
async def serverlist(ctx):
    if ctx.author.id == ownerID:
        msg = "\n".join(f"{x}" for x in bot.guilds)
        embed = Embed(
            title = "",
            description = "",
            color = col
        )
        embed.add_field(name = "All Bots Guilds", value = f"```\n{msg}\n```")
        await ctx.send(embed = embed)

What should I type to use this command

#

How to fix

#

ownerID ?

uncut ruin
#

so i should probably solve those...

slate swan
boreal ravine
uncut ruin
slate swan
#

Replit

pliant compass
slate swan
slate swan
pliant compass
#

Fancy

boreal ravine
slate swan
#

Since my laptop broken

uncut ruin
slate swan
plain shadow
# slate swan

if you do client = discord.Client then you must use client.guilds and not bot.guilds

boreal ravine
slate swan
#

Everything

plain shadow
slate swan
#

can I add bot = commands.Bot(command_prefix="a!", intents=intents, status=discord.Status.online)

pliant compass
#

Where is ownerID coming from?

plain shadow
#

then embed is not dfined

slate swan
#

kk

plain shadow
#

from discord import Embed

#

ownerID and col are not defined too

slate swan
#

How to fix

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 188, in on_message
    await message.channel.send(content=None, embed=embed)
  File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
    await resp.start(conn)
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
    message, payload = await self._protocol.read()  # type: ignore
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
    await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe

plain shadow
#

wtf is that error lol

#

never seen it

pliant compass
slate swan
#

**aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
**

slate swan
#

??

slate swan
#

just gotta figure out whats causing it

pliant compass
boreal ravine
#

o

slate swan
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 170, in on_message
    while "redgif" in post.url or ".gifv" in post.url:
  File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
    await resp.start(conn)
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
    message, payload = await self._protocol.read()  # type: ignore
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
    await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer

Another error right here

#

**while "redgif" in post.url or ".gifv" in post.url: **

was the last traceback and error is

aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer

#

ah

#

figured it out

#

the while loop makes too many requests

#

too fast

livid hinge
# slate swan How to fix
ownerID = 0
from discord import Embed
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))

@bot.command(help = "Shows the Guild the bot is in")
async def serverlist(ctx):
    if ctx.author.id == ownerID:
        msg = "\n".join(f"{x}" for x in bot.guilds)
        embed = Embed(
            title = "",
            description = "",
            color = col
        )
        embed.add_field(name = "All Bots Guilds", value=f"β€Š\n{msg}\n")
        await ctx.send(embed = embed)
``` this kind of fix.. all the stuff that's underlined needs to be defined (set as in a variable) or imported (like `Embed`)
maiden fable
unkempt canyonBOT
stark geyser
#

@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Your not in a voice channel")
voice_channel = ctx.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)

maiden fable
#

!d discord.ext.commands.Bot.application_info

unkempt canyonBOT
#

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

Retrieves the bot’s application information.
stark geyser
#

voice_channel = ctx.voice.channel i have a problem with this line any1 can help

#

voice has no attribute

maiden fable
#

!d discord.Member.voice

unkempt canyonBOT
#

property voice: Optional[discord.member.VoiceState]```
Returns the member’s current voice state.
maiden fable
#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

maiden fable
#

It should be ctx.author.voice.channel

unkempt jewel
#

im looking for some gud apis

#

can someone suggest ._.

boreal ravine
#

this for discord-bots

tawdry perch
boreal ravine
#

!ot

unkempt canyonBOT
unkempt jewel
#

cause my api for vtuber image now took me about 5000ms to send

unkempt jewel
boreal ravine
#

shit api 😐

tawdry perch
unkempt jewel
unkempt jewel
tawdry perch
unkempt jewel
#

kayle

unkempt jewel
#

API for my discord bot

lunar quail
#
    @commands.command()
    async def foo(self, ctx):
        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://cdn.discordapp.com/emojis/742284778409164801.gif") as r:
                res = await r.content()
                
            await ctx.send(res)

Error :

Traceback (most recent call last):
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 882, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 910, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 182, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'StreamReader' object is not callable

I wanted the bot to send image in the provided url, I'll also want to pass this as a parameter inside create_custom_emoji like ctx.guild.create_custom_emoji(..., image=res, ...)

What am I doing wrong here?

boreal ravine
rare saddle
#

How do I make a handler for this command?

boreal ravine
unkempt jewel
maiden fable
unkempt jewel
#

kayle is a champion in LOL

#

so i think u play ._.

boreal ravine
boreal ravine
livid hinge
rare saddle
lunar quail
# boreal ravine content is an attribute I think

yes it is, the discord docs wanted me to pass in a byte like object but I am not sure how to do that using aiohttp, I've checked attributes of clientResponse under aiohttp to see anything related to byte like object but to no avail

#

:(

tawdry perch
#

never seen greyblue in this channel before

rare saddle
#

How do I find the owner of the guild?

tawdry perch
unkempt canyonBOT
tawdry perch
#

uh maybe this

#

wait no

#

you asked guild 🀦

rare saddle
boreal ravine
tawdry perch
lunar quail
#

also

#

you need member intents for that

#

you have to enable it from the discord dev portal

rare saddle
#

yea, thanks

lunar quail
#

and enable it in your bot

boreal ravine
lunar quail
lunar quail
frank spoke
#

So my bots occasionally for some reason have a "breakdown" as I like to call it, where I'm suddenly getting errors that supposedly are from inside a package's file, and this time it even caused commands like pip list to stop working. I have set up a backup of the bot so it can still be used, but I'd like to know what's going wrong. It may be related to the asyncio package, as I've been able to fix issues by commenting it out, but I'm not sure if that package is actually important/used in my code, as some of my bots have it and others don't. I can't even remember when and why I added it... Let me know if you need any more information.
Error message: https://paste.pythondiscord.com/piwideyazu.sql

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.

plain shadow
frank spoke
lost wolf
#

File "/home/allans/NeoBot Premium/cogs/sharding.py", line 13, in update_database latencies = self.bot.latencies AttributeError: 'Bot' object has no attribute 'latencies'

#
from discord.ext import commands as cmd
import traceback
import asyncio
from datetime import datetime


class Sharding(cmd.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.bot.loop.create_task(self.update_loop())

    async def update_database(self):
        latencies = self.bot.latencies
        if len(self.bot.shard_ids) == 0:
            return

        cluster_id = self.bot.shard_ids[0] % self.bot.config.per_cluster
        shards = {id: {
            "latency": latency,
            "guilds": 0,
            "users": 0,
            "seen": datetime.utcnow(),
            "cluster": cluster_id
        } for id, latency in latencies}
        for guild in self.bot.guilds:
            try:
                shards[guild.shard_id]["guilds"] += 1
                shards[guild.shard_id]["users"] += guild.member_count
            except:
                pass

        for id, shard in shards.items():
            await self.bot.db.shards.update_one({"_id": id}, {"$set": shard}, upsert=True)

    async def update_loop(self):
        while not self.bot.is_closed():
            try:
                await self.update_database()
            except Exception:
                traceback.print_exc()

            await asyncio.sleep(60)


def setup(bot):
    bot.add_cog(Sharding(bot))
lunar quail
plain shadow
#

f

slate swan
frank spoke
#

What do I even need asyncio for? What is it used for?

lunar quail
#

Is there some wizardry where we convert StreamReader to byte like object? CH_Dead

slate swan
#

idk if it would work doe

slate swan
boreal ravine
slate swan
#

so basically everything you do in it is asyncio

frank spoke
#

But do I need to import asyncio in my code?

slate swan
#

no

frank spoke
#

So I can just throw that line out of- well this is confusing

slate swan
frank spoke
#

Yes or no?

slate swan
bleak karma
#

loaded the cogs but it wont recognize the commands inside the cog, what do i need to fix?

frank spoke
#

Actually it gives errors when I do import it

frank spoke
#

In fact, it even starts to give errors when I'm just trying to pip list... Somehow

slate swan
lunar quail
# slate swan try this: ```py import io res = io.BytesIO(res) await ctx.send(file = discord.F...
    @commands.command()
    async def foo(self, ctx):
        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://cdn.discordapp.com/emojis/742284778409164801.gif") as r:
                res = r.content
                
                res = io.BytesIO(res)
                await ctx.send(file = discord.File(res))

Error :

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: a bytes-like object is required, not 'StreamReader'
slate swan
frank spoke
slate swan
#

yo kale

frank spoke
#

But it's a private repl

slate swan
#

well atleast its private

#

replit is really unstable and buggy , thats the issue
if you run the same code on your device it will run well

#

yesh replit bad doe

maiden fable
maiden fable
frank spoke
#

I'm running literally the exact same code with the asyncio commented out and it's perfectly fine

boreal ravine
slate swan
maiden fable
#

iirc Private Repls got a dedicated IP

maiden fable
slate swan
#

id never go for it and get a vps instead :^)

frank spoke
#

I can't run it on my own device. The bots need to be up 24/7, I'm just someone living with their parents doing this in their free time, I'm not allowed to leave my laptop on all the time to run like 5 bots.

slate swan
slate swan
#

why did you import it there?

slate swan
slate swan
bleak karma
frank spoke
#

I literally stated:
-I don't know if I need it, which is why I came here
-I don't remember why I added it

bleak karma
#

this and um

slate swan
#

show your cog?

#

thats why

bleak karma
#

a im still new sorry

slate swan
#

the command is in the __init__ function

#

move the command function outside the init function

maiden fable
bleak karma
#

oh

slate swan
frank spoke
maiden fable
tough lance
#

lmao

slate swan
frank spoke
#

But do I fully need to swap to the backup? Because the old one seems completely broken, even after removing the line

slate swan
slate swan
#

you can

#

you can

#

but its messy af

#

I wouldn't say it's messy

frank spoke
#

Please. I already stated I can't just swap hosts.

slate swan
#

just put all the bots in the event loop and run it

frank spoke
#

And I'd probably need to rewrite a lot, as the bots share a lot of function names but with different responses.

slate swan
frank spoke
#

And fully swap to the backup?

slate swan
#

are you using asyncio

#

just use ctrl+f and search for asyncio

#

see if you need it

frank spoke
#

Well, I've transferred everything to that and removed the (already commented out) asyncio

frank spoke
#

So it's not mentioned anywhere else

slate swan
#

yea so you're cool with running it without asyncio

#
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
future: <Task finished name='Task-97' coro=<Message.delete.<locals>.delete() done, defined at /usr/local/lib/python3.8/dist-packages/discord/message.py:1014> exception=ClientOSError(32, 'Broken pipe')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/message.py", line 1017, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 544, in _request
    await resp.start(conn)
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client_reqrep.py", line 890, in start
    message, payload = await self._protocol.read()  # type: ignore
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/streams.py", line 604, in read
    await self._waiter
frank spoke
#

I've deleted the broken version

slate swan
#

hey

#

i get this error. any idea?

#

socket.send() raised exception.

#

hm

slate swan
pliant gulch
manic wing
#

you can stop your network with blocking code?

pliant gulch
#

Err I worded it wrong

#

But your most likely blocking your connection to discord

#

Like how you can block your bot from sending heartbeats to the gateway, essentially making "dead"

slate swan
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 170, in on_message
    else:
  File "/usr/local/lib/python3.8/dist-packages/discord/abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 192, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 1117, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/client.py", line 619, in _request 
    break
  File "/usr/local/lib/python3.8/dist-packages/aiohttp/helpers.py", line 656, in __exit__
    raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
boreal ravine
#

it isnt an error

#

its caused by the timeout from wait_for

#

iirc

pliant gulch
#

Read the traceback

#

It's coming from send_message

tawdry perch
#

Interaction timeout?

plain shadow
#

yep

cinder horizon
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'id'
```i get this error wen i try this in wavelink cogs...
my code
```py
async def play(self, ctx: commands.Context, *, track):
        """Play a song with the given search query.
        If not connected, connect to our voice channel.
        """
        if not ctx.guild.voice_client:
            vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
        else:
            vc: wavelink.Player = ctx.guild.voice_client
        tracks = await wavelink.YouTubeTrack.search(query=f"{track}")
        if not vc.is_playing():
            await vc.play(tracks)
            await ctx.reply(f"Playing {tracks}", mention_author=True)
            return
        vc.queue.put(tracks)
        await ctx.reply(f"Added {tracks} to the queue.", mention_author=False)
        if track.startswith("https://open.spotify.com/"):
            if track.startswith("https://open.spotify.com/track/"):
                track = await spotify.SpotifyTrack.search(query=f"{track}", return_first=True)
                if not vc.is_playing():
                    await vc.play(track)
                vc.queue.put(track)
            elif track.startswith("https://open.spotify.com/playlist"):
                await ctx.send("playlist meh")
                async for partial in spotify.SpotifyTrack.iterator(query=f"{track}", partial_tracks=True):
                    if not vc.is_playing():
                        await vc.play(partial)
                    vc.queue.put(partial)
```how do i get this ryt?
tough lance
#

At which line are you getting the error?

#

@cinder horizon

cinder horizon
unkempt canyonBOT
#

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

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

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

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

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

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

i saw youtube somewhere in that

cinder horizon
manic wing
#

YouTubeTrack

cinder horizon
#

iz literally this....i dont get how this is ytdl

cinder horizon
# manic wing `YouTubeTrack`

soundcloud got no support for all the songs....turns out my taste for songs is UNIQUE...sooooooo yt is da last resort manz

maiden fable
#

Well wavelink also breaks ToS, sooo

cinder horizon
#

f fomme ig

slate swan
boreal ravine
#

theres a maintained one iirc

#

forked from original lavalink/wavelink

manic wing
#

lavalink

bleak karma
#

how do i make an error handler if the person doing the command doesnt have this role

boreal ravine
#

!d discord.ext.commands.CheckFailure this

unkempt canyonBOT
#

exception discord.ext.commands.CheckFailure(message=None, *args)```
Exception raised when the predicates in [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") have failed.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
raw latch
#

I have a small problem with my buttons, if I press the button on a server, it responds on the another one that pressed the button a moment ago. Any idea how can I solve this?

tough lance
#

Add a check function

#

Which lib tho?

cold sonnet
#
await self.bot.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(self.bot.get_guild(payload.guild_id).get_role(744645354640637974))
```I like this
boreal ravine
cold sonnet
#

none

#

absolutely no nonetype

slate swan
cold sonnet
#

I'll show you

slate swan
#

!d discord.RawReactionActionEvent.member

unkempt canyonBOT
cold sonnet
slate swan
#

ow yea

raw latch
velvet tinsel
#

Pycord πŸ•΄οΈ

maiden fable
#

hmm

slate swan
#

is there an alternative for on_ready?

#

cuz I need to send a message when the bot is up

maiden fable
#

No

#

U can make a task and set the count to 1

slate swan
#

and I shouldn't use on_ready right?

maiden fable
#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
slate swan
#

ah yes solution = more damn loops lagging the shit out of everything

maiden fable
#

Nah

slate swan
#

bots normal ping already 3k

maiden fable
#

You know... My bot (HunAI) got like 5 tasks or smth running and it is in 99 servers but the bot's ping is about 120 or smth

pliant gulch
#

How is ping relevant to compute time

tawdry perch
slate swan
#

hm

maiden fable
boreal ravine
#

i use replit and it has like 30ms how tf do you get 3k ms

maiden fable
#

LMAO

slate swan
#

bro

#

romanian servers

#

20€/year

maiden fable
#

Sooooo?

slate swan
#

4gb drr3 2cores e-5

tawdry perch
#

you can get a better one with 20 bucks if you got 3k latency from that

maiden fable
#

ping totally depends on your internet connection bro

slate swan
#

thats cheap asf

maiden fable
slate swan
#

1.3€ / month

pliant gulch
#

About 2 USD per month

tawdry perch
#

I host for free and I have better latency smh

maiden fable
#

ikr same

slate swan
#

hm

#

what u using

#

google cloud trial?

tawdry perch
#

good question

slate swan
#

aws?

tawdry perch
#

no it's 24/7 free for me, not trial

#

500mb free memory and 65%cpu (what ever that means)

pliant gulch
#

Probably a shared server?

maiden fable
slate swan
#

oh yea and its vds

#

so fuck sharing resources

cold sonnet
#

help I'm being meh
embed.set_footer(icon_url=f"{guy.avatar.url}, itt: {message.channel.mention}")

#

In embeds.0.footer.icon_url: Not a well formed URL.

tawdry perch
slate swan
#

80860.06ms rn

maiden fable
#

8 seconds tf?

cold sonnet
#

oh

pliant gulch
#

Ungodly speeds

cold sonnet
#

that should be in the text....

maiden fable
slate swan
#

and yet 35 ppl are using my bot lol

pliant gulch
#

I wouldn't even pay 2 USD a month for whatever service you are using. They would need to pay me to even make me decide to use it

tawdry perch
#

My avg latency is 80-100 (quite good imo for free)

quick gust
#

replit?

tawdry perch
#

no I don't use replit

#

anyways gotta study the next 2 mins till I be back again

quick gust
#

whatever host that is, is pretty good then

slate swan
pliant gulch
#

The only resource you really need to focus on is ram

#

Since all the caching is on the ram

tawdry perch
pliant gulch
#

E.g guilds, users, members

slate swan
pliant gulch
#

Yea,

#

But tbh you should just switch your service providers

#

E.g AWS, GCP, Linode etc

#

They should have servers where you are?

slate swan
#

I'm happy with the vds, it can 2 websites and 1 game server just fine. but for some reason my bot is just too much for it lol

#

I mean the websites are fast, no loading issues or anything

pliant gulch
#

Might just be a problem with your bot then?

slate swan
#

probably

pliant gulch
#

You should setup a simple bot and benchmark it, compare with your original bot

tawdry perch
#

you sure you don't use sync libs there and use async?

pliant gulch
#

If the difference is vast you probably are doing something wrong in your original bot

#

Otherwise, it would just be an internet issue ig?

slate swan
#

I mean the code is really messy, should probably rewrite it

maiden fable
slate swan
#

cuz I remember I had another bot, way more simple tho, max 30ms ping

maiden fable
#

@slate swan what is the website of the host?

slate swan
#

its some romanian random host

pliant gulch
slate swan
maiden fable
#

u r just wasting your money

tawdry perch
slate swan
#

yes they are probably even datamining the files but idc

#

i've got nothing important

pliant gulch
#

Probably why they are so cheap anyhow

tawdry perch
maiden fable
slate swan
#

dude the founder barely even knows english

#

and there is no other staff

pliant gulch
maiden fable
#

damn

pliant gulch
#

Usually services just sell telemetry data, and that's how they can provide such cheap services

maiden fable
#

and most of the times people don't know about it? or smth

pliant gulch
#

Yea most of the time ig

#

Discord also has telemetry

#

Don't even get me started on windows and telemetry

slate swan
#

he running his stuff in his basement

maiden fable
pliant gulch
#

Yea, I heard about it a while back for some stuff

#

Like when users call slash commands api/v9/science get's requested

#

Most likely telemetry or whatever

maiden fable
#

Well I did hear something related to NFT but never knew what was the whole story

maiden fable
#

Time to move to discord web again

pliant gulch
maiden fable
#

Ah okay

slate swan
#

bruh my bot keeps going offline, tho its still running

maiden fable
#

enable logging

uncut ruin
slate swan
#
#    running = False
@client.event
async def on_ready():
    for guild in client.guilds:
        for channel in guild.channels:
            if os.path.exists("/home/bot/adx/channel"+str(guild.id)) == True:
                file = open("channel"+str(guild.id), "r")
                if str(channel.id) == file.read():
                    file.close()
                    embed = discord.Embed(title="> __Channel inactive__", color=0xFF0000)
                    embed.add_field(name="Reason for inactivity", value="Restart by developer", inline=False)
                    embed.add_field(name="Note", value="Small bug fixes || Added new categories", inline=False)
                    await channel.send(embed=embed, delete_after=60)

                    break

this was working before, any idea why it isn't anymore?

#

fuck

uncut ruin
slate swan
#

How can I sleep 24h? I don't want to use seconds

uncut ruin
#

also no need to say if os.path.exists() == True, just say if of.path.exists()

slate swan
#

(It's a background task)

slate swan
uncut ruin
uncut ruin
slate swan
#

they ddr3

uncut ruin
final iron
slate swan
#

its some romanian dudes hosting company, he has his servers in his basement

uncut ruin
slate swan
#
@client.command()
@commands.check(is_it_me)
async def nicks(ctx):
    guild = client.get_guild(756504534897000528)
    while True:
        for member in guild.members:
            print(member)
            await member.edit(nick=f"βœ¨γƒ»{member.display_name}")

WHY THIS DOESN'T WORK!

uncut ruin
slate swan
uncut ruin
slate swan
#

Where is that

slate swan
final iron
#

That not a lot for server grade

slate swan
# maiden fable intents?
client = commands.Bot(command_prefix='?', case_insensitive=True, intents = discord.Intents.all())
uncut ruin
slate swan
#

It works for my welcomer

slate swan
#

But I can't do it manually

slate swan
slate swan
#

Guys could asyncio.sleep(86400) run into any issues?

final iron
slate swan
#

should I use time.sleep or asyncio.sleep inside a while loop

maiden fable
#

the latter

boreal ravine
#

which array should I use for a tree command for a marriage cog

slate swan
#

ok ty

quick gust
slate swan
#

WHY IT DOESN'T WORKKKK

final iron
bleak karma
#

wont send the embedded message and no error help?

slate swan
# maiden fable the latter

but asyinco.sleep doesn't stop the while loop, it just keeps repeating everything thats before the ayncio.sleep

slate swan
#

I think it has to be a string

boreal ravine
bleak karma
#

oh alr

slate swan
boreal ravine
slate swan
slate swan
slate swan
#

idk your error handler eats it maybe

bleak karma
slate swan
slate swan
boreal ravine
bleak karma
slate swan
bleak karma
#

wont give me an error

slate swan
#

I think the error is, Because it can't change the nick of owner

final iron
bleak karma
#

i find it a bit messy

boreal ravine
#

only kwargs afaik

final iron
#

I just threw it out there in case it did

boreal ravine
#

which array should I use for a tree command for a marriage cog

final iron
#

uhh... I'll get back to you on that

slate swan
#
@client.command()
@commands.check(is_it_me)
async def nicks(ctx):
    guild = client.get_guild(756504534897000528)
    while True:
        for member in guild.members:
            if member.display_name != "SamTheNoob":
                await member.edit(nick=f"βœ¨γƒ»{member.display_name}")
            else:
                pass

Im a fucking genius

maiden fable
#

wrong ngl

twin moon
#

can I use a async def to stop a command?

slate swan
maiden fable
#

!paste u can use this

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.

slate swan
#

How do you reset a nickname?

maiden fable
#

nick=None in member.edit

slate swan
#

"Something went wrong"

#

file too big or somthign idk

maiden fable
#

Wait what is the level?

slate swan
#

& browser froze

maiden fable
#

set the level to WARNING not DEBUG

slate swan
#

kk

twin moon
maiden fable
#

idts

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

whats the code so when i ping my bot it responds with its prefix (i use discord.py)

#

use on_message event

#

and check if <@!yourbot'sid> is in the message

final iron
maiden fable
#

facts

#

u using requests

final iron
#

2021-12-19 18:44:31,730:WARNING:discord.gateway: Shard ID None heartbeat blocked for more than 50 seconds.

maiden fable
#

that's the issue. use aiohttp

final iron
#

Doesn't this mean something is blocking (Not async)?

maiden fable
#

nvm its praw

final iron
#

Use asyncpraw

#

!pypi asyncpraw

unkempt canyonBOT
#

Async PRAW, an abbreviation for `Asynchronous Python Reddit API Wrapper`, is a python package that allows for simple access to reddit's API.

pliant gulch
maiden fable
#

or why not use the JSON API

slate swan
#

praw easier

final iron
#

Understandable

pliant gulch
#

Isn't asyncpraw litteraly just praw but async

final iron
#

Yes

pliant gulch
#

Like all the methods, classes etc are the same lol

#

How would that be any harder

slate swan
cold sonnet
#

if on_member_ban as an event is not accessed, does that mean it never gets called in the source code?

pliant gulch
#

Ah

final iron
#

I think he meant using asyncpraw/praw is easier than working with raw JSON data

honest shoal
#

I made a restart command it successfully restarts the bot, how can I make it edit that Rebooting message to Done after successful reboot here's the code py @bot.command() async def restart(ctx): ctx.message.author == "787149777103486986" await ctx.send("**Rebooting** ![malloading](https://cdn.discordapp.com/emojis/922167995961335808.webp?size=128 "malloading")") os.system("clear") os.execv(sys.executable, ['python'] + sys.argv)

final iron
honest shoal
cold sonnet
#

and .id returns an int, not a string

honest shoal
#

hmm

cold sonnet
#

and ctx.author is enough

honest shoal
#

yeah I'm aware

honest shoal
final iron
honest shoal
#

just fixed

final iron
honest shoal
#

oh oke

slate swan
#

fck

#
    while True:
        for member in guild.members:
            try:
                if member.nick.startswith("✨"):
                    pass
                else:
                    await member.edit(nick=f"βœ¨γƒ»{member.display_name}")
            except:
                pass

Will it pass if it's already done?

maiden fable
cold sonnet
#

while True peepoDetective

slate swan
#

what should I use

#

?

cold sonnet
cold sonnet
slate swan
#

urgh...

cold sonnet
#

where's the path to tasks

maiden fable
cold sonnet
#

oh

#

I need some sleep

slate swan
#

ok what ever

final iron
#

huh

slate swan
#

thanks for the help

maiden fable
#

!d discord.ext.tasks.Loop @final iron

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
maiden fable
#

ext.tasks is the submodule

final iron
#

Ah

cold sonnet
#

I also got 4 undefined errors after deindenting

#

where brain

maiden fable
#

Lmao

cold sonnet
#

but I wrote 300 lines in 2 hours so I think it's acceptable

slate swan
#

ofc i cant fucking .random() in asyncpraw

#

fuckingfuck

cold sonnet
#

language

slate swan
#

do i need to rly use for loop

#

hunter dude give solution

maiden fable
#

Idk what u tryna do, soo uhhhh

slate swan
#

what I could have done before to get random submission from a subreddit

sub = reddit.subreddit("insertnsfwsubreddithere").random()

What i gotta do now

sub = await reddit.subreddit("insertnsfwsubreddithere")
async for submission in sub:
full valley
#

How can I compare the datetimes of when a vc was created, and when 'the' command is issued

slate swan
maiden fable
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
full valley
maiden fable
pliant gulch
#

datetime <comparison opertor> datetime

#

E.g datetime > datetime

full valley
maiden fable
#

andy gave u the answer πŸ˜„

slate swan
#

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 206, in on_message
post = random.choice(postr)
File "/usr/lib/python3.8/random.py", line 288, in choice
i = self._randbelow(len(seq))

full valley
maiden fable
#

try doing (await reddit.subreddit(...)).flatten()

full valley
#

at least 5 minutes wouldnt simply be if datetimenow >= datetime_of_creation + 5 right? KEKW

#

since its an object

slate swan
maiden fable
#

edited my message

upbeat otter
#

guys, how do I make it return the time only ,-,

for act in member.activities:
        if isinstance(act, discord.Spotify):
            embed = discord.Embed(title=f"{member.name}'s spotify status", color=member.color)
            print(act.start.astimezone(pytz.timezone("Asia/Calcutta")))
slate swan
#

AttributeError: 'Subreddit' object has no attribute 'flatten'. 'Subreddit' object has not been fetched, did you forget to execute '.load()'?

maiden fable
#

I just lost 5 braincells seeing that code

upbeat otter
slate swan
#

fuck this I'll use the annoying for loop

maiden fable
#

bruh

slate swan
#

why can't asyncpraw have .random()

lament mesa
# cold sonnet

dpy internally calls the events, your linter doesn't know about that

maiden fable
#

!d datetime.datetime.minute

unkempt canyonBOT
maiden fable
#

!d datetime.datetime.hour

unkempt canyonBOT
maiden fable
#

!d datetime.datetime.second

unkempt canyonBOT
cold sonnet
#

it was.... indented wrong

upbeat otter
#

really not helpful of what I was trying to do

maiden fable
#

I told u the issue tho pepe_thinks

cold sonnet
#

discord.Spotify?

upbeat otter
maiden fable
lament mesa
maiden fable
cold sonnet
#

I see

maiden fable
#

!d discord.Spotify

unkempt canyonBOT
#

class discord.Spotify```
Represents a Spotify listening activity from Discord. This is a special case of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that makes it easier to work with the Spotify integration.

x == y Checks if two activities are equal.

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

hash(x) Returns the activity’s hash.

str(x) Returns the string β€˜Spotify’.
maiden fable
#

istg google colab gonna make me pull all my hair out

slate swan
#

hahaa wtf by breaking something I fixed the message I had on_ready

#

no idea what I even did

#

but it worked

#

lovely python

maiden fable
#

it fixed cz u had blocking code

#

!blocking for more information

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

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

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

cant be that cuz it was working before

full valley
#

@maiden fable Does the .minutes attribute return an integer for datetime?

full valley
#

easy

slate swan
#

also thx huntering

maiden fable
#

!e

import datetime
time = datetime.datetime.utcnow()
print(time.minute)
print(type(time.minute))
unkempt canyonBOT
#

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

001 | 25
002 | <class 'int'>
mighty dust
#

what datatype does context.author return?

maiden fable
#

See

maiden fable
unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
maiden fable
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

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

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
maiden fable
#

Depends if the command is in DMs or Guild

mighty dust
#

hmm

maiden fable
mighty dust
#
if context.author = "PythoNub#8527":
#

this should work right?

maiden fable
#

No

unkempt canyonBOT
maiden fable
#

compare this

mighty dust
#

tysm

#

not working

maiden fable
mighty dust
#

okey

maiden fable
#

Wait

#

what is yr code

slate swan
#

how do I get the purple streaming status

mighty dust
#
@client.command(name = "terminate")
async def terminate(context):
    print(str(discord.User.name))
    if discord.User.name == "PythoNub#8527":
        import sys
        embed = discord.Embed(title = "Shutting down :(")
        embed.set_footer(text = context.author + "killed me ")
        await context.message.channel.send(embed=embed)
        sys.exit()
    else:
        embed = discord.Embed(title = "Haha Nice try")
        embed.set_footer(text = ":)")
        await context.message.channel.send(embed = embed)
slate swan
unkempt canyonBOT
slate swan
#

@slate swan ^

mighty dust
slate swan
#

what should I put in discord.Status then?

maiden fable
slate swan
#

cuz activity should only give streaming: thing

maiden fable
unkempt canyonBOT
maiden fable
#

ah wrong

#

u need an instance of discord.User

#

and context.author returns one

mighty dust
#

i dont understand

sage otter
#

Why are you only comparing .name

#

He needs name and discrim

maiden fable
#

yea that too

slate swan
mighty dust
#

will message.author.username work

#

ohh

cold sonnet
#

how would I convert a set that has one object to a role object

#

wait

#

I just take set_name[0]

mighty dust
#

;(

quick gust
#

!d discord.Message.author

unkempt canyonBOT
cold sonnet
velvet tinsel
#

That’s my boy/girl

craggy cloak
#

How to fix this?

velvet tinsel
craggy cloak
#
        sec = round(error.retry_after)
        cooldownembed = discord.Embed(title="", color=discord.Color.blue())
        cooldownembed.add_field(name="⏲️ Cooldown",value=f'The command {on_command_error} is still on cooldown for **{convert(sec)} Seconds**'.format(ctx.command.name, error.retry_after))

slate swan
maiden fable
#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
#

Wait

#

The link is broken?

#

Or is it just my client

honest shoal
#

hey how can I make people with admin permissions bypass the channel in which command is supposed to be used, suppose this is my code ```py
@bot.command()
async def hi(ctx):
if ctx.channel.id == 917866202968236052:
return
await ctx.send("Hi")

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

echo lagoon
#

Using dpy2.0 trying to add a button before a select dropdown in my view, getting an error as drop-down size is 5, adding a button to that row surpasses the limit

How would I go about fixing said issue?

#

(I would like to move the drop-down 1 row down)

torn sail
echo lagoon
honest shoal
#
@bot.command()
async def hi(ctx):
if ctx.channel.id == 917866202968236052:
ctx.channel.permissions_for(ctx.author).administrator
        return
    await ctx.send("Hi")``` do you mean like this?
slate swan
honest shoal
torn sail
echo lagoon
torn sail
slate swan
slate swan
# echo lagoon I've already written most of my bot, what benefit would I have using a fork?

Well most forks have better buttons and you will not need any third party lib and most forks have slashcommands and especially disnake is always up to date and is not hard to change to it you just replace the word discord with disnake and your basically working with disnake already or you can just import disnake as discord which i dont quite recommend but buttons for disnake are very easy and have github examples if you have any questions about them

honest shoal
slate swan
torn sail
honest shoal
maiden fable
echo lagoon
slate swan
echo lagoon
slate swan
#

which I cant remove

echo lagoon
#

Mhm

maiden fable
slate swan
#

well fuck

#

then I've got quite a problem huh

slate swan
maiden fable
#

Facts

slate swan
#

maybe if I make a timer, so when it reaches 90seconds it breaks and starts again after running the whole code?

echo lagoon
honest shoal
#

@torn sail colon shows invalid syntax

slate swan
echo lagoon
torn sail
honest shoal
torn sail
#

can you screenshot ur code?

maiden fable
#

shouldn't be more than 5-10s

honest shoal
echo lagoon
#

Using task.loop decorator

honest shoal
#

This is spam command restricted to a single channel, but I just want admins to use it in any channel py @bot.command() @commands.cooldown(1,30,commands.BucketType.guild) async def spam(ctx, amount : int, *, message=None): if ctx.channel.id == 917866202968236052: return limit = 15 if amount > limit: await ctx.send(f"<:_:919194636906561548> **The amount provided `{amount}` is too big! It needs to be less then 15.**") return else: for _ in range(amount): await ctx.send(message)

echo lagoon
#

Welp you'll need to specify the repeat rate tho

echo lagoon
torn sail
honest shoal
echo lagoon
torn sail
indigo tusk
#

Can someone explain to me why its not defined even after I defined it?

tawdry perch
indigo tusk
torn sail
tawdry perch
indigo tusk
torn sail
honest shoal
#

but it doesn't work shows invalid syntax

torn sail
honest shoal
echo lagoon
#

found it, something like this for custom check:

    def is_guild_owner():
        async def predicate(ctx):
            if not ctx.guild.owner_id == ctx.author.id:
                raise commands.CommandError("This command can only be used by server owner!")
            return True
        return commands.check(predicate)
torn sail
tawdry perch
#

it seems like so

torn sail
echo lagoon
#

^

slate swan
#
                now = datetime.now()
                current_time = now.strftime("%S")
                while m:
                    current_time2 = now.strftime("%S")
                    current_time3 = int(current_time)
                    current_time3 += 10
                    while current_time3 >= int(current_time2)

too confusing for me, would this work

#

as a timer

echo lagoon
#

what is the timer for?

#

(interaction check?)

echo lagoon
#

hold up, i think i got something

slate swan
#

cuz its infinite loop

#

and im tryna break the loop when 10s has passed

upbeat otter
slate swan
#

and create task was too complicated for me

echo lagoon
#
timeout = time.time() + 60
while True:
    await asyncio.sleep(0.1)


   if (timeout < time.time()):
      #do something
upbeat otter
#

A task loop is an async version of a while loop

slate swan
#
@bot.command()
async def sendp(ctx):
    guild = bot.guilds()
    for member in guild.members():
        print(member)

``` why does not work ;/ 
```    ret = await coro(*args, **kwargs)
  File "c:\Users\sdziu\Desktop\Python\Discord\nsfw_bot.py", line 27, in sendporn
    guild = bot.guilds()
TypeError: 'list' object is not callable```
slate swan
honest shoal
#

well thx my issue is fixed @torn sail

torn sail
#

And In guild.members

echo lagoon
# upbeat otter Not if, while*

0.o welp, pulled it from my code, tho its got couple other paramaters to break on, while also adding to the timeout . - .

echo lagoon
#

well, its a loop that never ends

slate swan
torn sail
slate swan
#

yeh

#

timeout = time.time() + 60
while autoporn:
await asyncio.sleep(0.1)
if (timeout < time.time()):
if message.channel.is_nsfw():
else:
break?

torn sail
echo lagoon
#

srry

slate swan
# torn sail Is the error the same?

yeh raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'members'

slate swan
upbeat otter
slate swan
#

damn this gonna suckk never used em before

torn sail
maiden fable
#

Rip istg I will lose my sanity soon

#

Ping

maiden fable
slate swan
#

reading these messages gives me a headache

maiden fable
torn sail
#

@slate swan so bot.guilds returns are list of guilds and the list doesn’t have an attribute members but if you go through each guild then the guild will have an attribute members

upbeat otter
upbeat otter
maiden fable
#

ahem ahem can we stop this ahem ahem

slate swan
upbeat otter
#

||!ot||

torn sail
slate swan
#

then what do i do lmfao

slate swan
torn sail
upbeat otter
#

oof

maiden fable
# slate swan > ___~~**yes**~~___

Look okay its already 12 midnight here and I am already on the edge of losing my sanity so it would be better if u don't joke with me rn with all those things, thanks

maiden fable
upbeat otter
slate swan
#

Imagine

#

Its 2:29pm for me

#

20:29

slate swan
#

anyways

upbeat otter
slate swan
#

uh

torn sail
upbeat otter
#

!d discord.ext.tasks.loop @slate swan

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").
upbeat otter
#

Welcome

slate swan
#

aight cheers

#

ok where and how and yes

upbeat otter
#

See the docs