#discord-bots

1 messages Β· Page 551 of 1

rugged marsh
#

Then how do you know that his playlist sounds edgy? ?:)

boreal ravine
#

you can't

#

common sense

lusty swallow
rugged marsh
lusty swallow
rugged marsh
#

-.-

#

just don't

boreal ravine
lusty swallow
#

i think you minunderstood me here. When kayle said "people stalking people's spotify now?", i replied with just his like i only stalked his SA and his SA only

slate swan
#

What Playlist yert

rugged marsh
#

oh

#

;-;

lusty swallow
#

getting ot

#

!ot

unkempt canyonBOT
rugged marsh
#

snap back to the channel's topic

valid galleon
#

can someone tell me how i can make an afk command with sqlite3? ive tried making it on my own, but its glitchy af. maybe you can recommend some tutorials or smthng? if its in a different db, like postGRE, i'll convert it to sqlite i just need some reference

#

or can you link the repo of a bot with an afk command?

brazen raft
#

Well first of all, you should use an asynchronous library. Maybe aiosqlite, or asyncpg if you prefer PostgreSQL.
Now... What is an afk command?

valid galleon
#

now that i think about it, i think the reason it fucked up is cuz i didnt use the async version of sqlite lol

ocean leaf
#

how can i update my discord.py version to 2.0 in replit?

maiden fable
inner geyser
boreal ravine
valid galleon
#

how do i stop the bot from deleting the user's messages when banning?

maiden fable
unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
maiden fable
#

There's a delete_message_days kwarg

#

Use that

valid galleon
#

alright thanks

urban shell
#

hey guys, I am working on a music bot, I'm currently using yt-dl to source the audio, is there a way to use Spotify or some other source with a better audio quality for the same?

boreal ravine
urban shell
#

I rarely refer yt for projects

boreal ravine
#

sure you didn't

urban shell
#

bruh

slate swan
boreal ravine
#

theres been a lot of people asking for help about youtube_dl here

#

and I found the video they got the code from he didn't even explain what the code did

slate swan
#

You can't

slate swan
#

You could make a global var and change it in the command tho

urban shell
#

I'm not asking for help with yt_dl

slate swan
#

The rest i improved 😎

heavy folio
#

bruh

slate swan
#

Yes

#

Just the configuration

heavy folio
#

thats not how it works

slate swan
#

The commands and the logic I made myself

slate swan
boreal ravine
#

oh

#

the examples good

slate swan
slate swan
boreal ravine
#

@slate swan your russian?

slate swan
#

No

boreal ravine
#

hm

urban shell
#

what made you jump to that conclusion

slate swan
#

^^

boreal ravine
#

idk

urban shell
#

bruh

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)
slate swan
#

Like I even have a link in my bio which has some info about me πŸ˜”βœŠ

proud glade
#

not sure if you can lol, just do the counting in the task itself then stop it

boreal ravine
#

same thing goes for spotify

slate swan
#

The long awaited !ytdl

urban shell
slate swan
boreal ravine
#

iirc

slate swan
proud glade
#

good luck downloading stuff from spotify lol

slate swan
#

It's not the same

urban shell
slate swan
#

Ytdl != Spotify

reef shell
#

I meant the ToS

slate swan
slate swan
#

Spotify has the same thing in their ToS?

#

Probably yeah

#

Why would they accept something like that kekw

urban shell
#

"Probably"

slate swan
#

"probably"

urban shell
#

there's Deezer

#

Soundcloud

slate swan
#

🦜 🦜

reef shell
#

Spotify doesn’t support streaming audio source like tgat

urban shell
#

and so many other sources out there

heavy folio
#

i mean its kinda common sense, if spotify doesnt do the same then they're losing money too

urban shell
#

I was just asking for your opinion

boreal ravine
#

copying, reproducing, redistributing, "ripping," recording, transferring, performing, framing, linking to or displaying to the public, broadcasting, or making available to the public, or any other use which is not expressly permitted under the Agreements or applicable law, or which otherwise infringes intellectual property rights;
https://www.spotify.com/us/legal/user-guidelines/?_ga=2.74992274.1463521725.1634807135-1556900206.1632746656

urban shell
#

and if someone has worked on a similar project

restive verge
#

who pinged

reef shell
#

The music bot's do take the title and author name from spotify and search it up on youtube to get the song, eventually leading to use ytdl

boreal ravine
#

discord added it for a reason

slate swan
#

It's just so obvious that streaming platforms don't like their service to be streamed

#

Not rocket science

urban shell
slate swan
#

Specifically when they make profit from their service

boreal ravine
#

^

#

rythm/groovy had premium iirc

restive verge
reef shell
boreal ravine
reef shell
rugged marsh
#

lol, they will develop their own bot and put audio ad in

reef shell
#

discord will be releasing a new feature regarding this, It's called youtube together which will allow you to watch yt videos in vc

urban shell
#

xDD

reef shell
#

And that includes adoooof

urban shell
#

not looking forward to it

boreal ravine
#

bypassing ads

#

spotify said something about that iirc

urban shell
#

ad-blockertroll

boreal ravine
#

u cant use ad blocker on spotify

urban shell
#

yes......

boreal ravine
#

yes

urban shell
#

I was talking about yt

boreal ravine
#

oh

urban shell
#

nvm

boreal ravine
#

cool

urban shell
#

anyways

#

chat's going ot

slate swan
rugged marsh
#

ah yes

#

I don't like my voice being collected to youtube

boreal ravine
#

nice

#

bruh

#

!ot

unkempt canyonBOT
rugged marsh
#

quite cool tho

devout quest
#

how to edit msg tho

#

py discord

boreal ravine
unkempt canyonBOT
#

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

Edits the message.

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

Changed in version 1.3: The `suppress` keyword-only parameter was added.
devout quest
#

ok

#

how to delete msg

maiden fable
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
devout quest
#

ok

#

how to select the msg to delete

#

can u help me out with the edit msg

lament mesa
devout quest
#
    
    await message.channel.send("https://images-ext-2.discordapp.net/external/r_HR-WHA2AzKT3y9NwUWCCiWCpKH440-5B_0_sxrcm4/https/i.imgur.com/w5vm9l8.mp4")
    time.sleep(5)
    async def on_message(message):
      if 'https://imgur.com/qJyjIIN' in message.content:
        await message.edit(message,"https://imgur.com/qJyjIIN")```like this
#

lmao

valid perch
#

try it and see

devout quest
#

uh

valid perch
#

But no, you dont pass the message, only the content you want to edit

devout quest
#

no work, just the first part444

sudden moss
#

Does anyone know how to make slash commands in py-cord? I tried to use the code from the example but it didn't work

valid perch
#

Well you dont call the function you define

devout quest
#

ok

#

if message.content.startswith("g!wish"):

await message.channel.send("test")
async def on_message(message):
if 'test' in message.content:
    await edit(message, "testtest")

help

valid perch
#

Why u defining another function...
async def on_message(message):

devout quest
#

oh

#

ok

#

so i just need to delete that

valid perch
#

try it

devout quest
#

ok

#

work the first part only

#

only gib me test

#

not testtest

#
if message.content.startswith("g!wish"):
    
    await message.channel.send("test")
    
    if 'test' in message.content:
       await edit(message, "testtest")```
proud glade
#

await message.edit("new content")

#

is the correct syntax

devout quest
#

uh

proud glade
#

also, by the way

#

you're checking if "test" is in the original message's content

#

not the message you sent right above that

devout quest
#

ok

#

what is original msg content

#

can u tell me pls

proud glade
#

... the message.content

devout quest
#

ok

#

uh can u fix my code

#

srry

#

oh

proud glade
#

well no, i'm not going to spoonfeed you, but i'm here to help

devout quest
#

why

proud glade
#

that's not the correct syntax

devout quest
#

can u help me with the syntax

proud glade
devout quest
#

k

#

bruh

proud glade
#

oh wait

devout quest
#

oh, i deleted the if

#

or wtv

#

right, is that matters

proud glade
#

apologies, i made a slight mistake

devout quest
#

np

proud glade
#

you need to put the new message as content

#

await message.edit(content="new content")

devout quest
#

oh

#

why i need that

proud glade
#

because it's how the library works

devout quest
#

oh, ok

proud glade
#

yeah, look at the docs instead

devout quest
#

lmao,still cant

#

hehe

#
if message.content.startswith("g!wish"):
    await message.channel.send("test")
    if 'test' in message.content:
      await message.edit(content="testtest")```
#

lmao

valid perch
#

You can only edit messages you sent (you being the bot....)

dapper cobalt
valid perch
#

Your also still only checking the original message. as you were told before but πŸ€·β€β™‚οΈ

#

We dumb dumb

dapper cobalt
#

Are you using message events to make commands?

slate swan
#

Yes

devout quest
#

im editing my own msg now

proud glade
valid perch
#

So you can edit everyones messages? Shesh

slate swan
devout quest
#

heh

valid perch
devout quest
#

oh

#

ok

slate swan
#

You can only edit messages YOU send

#

Meaning the logged in user/bot

devout quest
#

uh,lmao

slate swan
#

I mean

#

It's quite logical

devout quest
#

i know, the bot is editing its own msg

slate swan
#

And that's the only messages your bot can edit

devout quest
#

yeh

#

im coding it to edit that

#

if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")

#

like it send test and edit it to test test

#

lmao, what should i do

#

what

#

yeh, i try

#

no error but no fix

#

ok

#

but where, send me the link

#

i like watching tuto but not reading

#

uh, ok ty

#

oh

#

i saw 1ty

final shard
#

why is the command not getting deleted in one server

@bot.command()
async def say(ctx, *, arg):
  await ctx.send(arg)
  await ctx.message.delete()
#

in my test server the bot deletes the trigger

#

but in only one server it doesnt get deleted

slate swan
#

does the bot have manage_messages perm in that server?

final shard
slate swan
#

Well, if it works in one but not in the other then it's a problem with the other sever's bit permissions

final shard
#

oh hm

#

maybe i should try other methods for delete?

slate swan
#

No, what you should try is fixing the problem in that other server

final shard
#

I made it rejoin

#

it got admin

#

also im not the owner

#

my friend is the owner

muted pier
#

Hi

devout quest
#

hi, how to make the bot edit it msg

#

i watch all tuto in youtube but nothing

boreal ravine
boreal ravine
unkempt canyonBOT
#

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

Edits the message.

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

Changed in version 1.3: The `suppress` keyword-only parameter was added.
devout quest
#

uh

boreal ravine
#

yk if you dont understand just ask Β―_(ツ)_/Β―

devout quest
#

lmao, dont understand

#

if message.content.startswith("g!wish"):
await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")

#

it just show test not testtest with edited

boreal ravine
devout quest
#

uh how, can u teach me

boreal ravine
#

then edit it using await variable.edit("testest")

boreal ravine
devout quest
#

i know how to make a variable tho but

#

if message.content.startswith("g!wish"):
bruh = await message.channel.send("test")
if 'test' in message.content:
await message.edit(content="testtest")

devout quest
#

but what to save

#

hey kayle

#

@boreal ravine

boreal ravine
devout quest
#

how

#

and put bruh.edit in where

#

like u want me to save???

boreal ravine
devout quest
#

ih

#

ok

#

i know how to make a variable tho but
if message.content.startswith("g!wish"):
bruh = await message.channel.send("test")
if 'test' in message.content:
await bruh.edit(content="testtest")

#

like this

devout quest
valid perch
#

try it and see

boreal ravine
#

^

valid perch
#

You can also send us errors..

devout quest
#

i try it

valid perch
#

Fix your indentation so its all in line

devout quest
#

???

boreal ravine
#

ok

valid perch
#

This is fairly basic python

boreal ravine
#

@devout quest pls learn more python

valid perch
#

!indent

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

devout quest
#

ugh

valid perch
#

If you don't understand indentation you need to learn more python. This is the basis of the entire language

devout quest
#

ugh

#

Tjwearfkefewercerccrc

#

ertedc

#

gwg

valid perch
#

Imagine having to learn someting. Sorry

devout quest
#

yeh

boreal ravine
#

L

valid perch
devout quest
#

ok

valid perch
#

But go learn some more python first, otherwise I won't be helping for my own sake

devout quest
#

ok

#

what should i learn to do it

boreal ravine
valid perch
#

<@&831776746206265384> ^

arctic python
#

!mute 789832854258450434 24h Refrain from spamming.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @devout quest until <t:1634976339:f> (23 hours and 59 minutes).

slate swan
#

hi

#

im back

#

why i get 24h but it is my first warning

#

bruh

valid perch
#

@arctic python ^

slate swan
#

πŸ˜‚

#

???

valid perch
#

Dm @novel apex if you want to talk about infractions

arctic python
#

!ban 644523101257728020 Ban evasion, alt of 789832854258450434

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @dense granite permanently.

arctic python
#

!ban 789832854258450434 Ban evasion, alt of 644523101257728020

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @devout quest permanently.

slate swan
#

Isn't it "mute evasion" thinkmon

arctic python
#

You get the idea

slate swan
#

Well, yeah

boreal ravine
#

"bruhmao" "hu tao"

sudden moss
slate swan
#
async def on_member_join(member):
   await bot.get_channel(891878891889766414).send(f"welcome **{member.mention}!**")```
how would i be able to turn this welcome message into an embed?
boreal ravine
sudden moss
#

embed = discord.Embed(description=f"Welcome **{member.mention}**")

boreal ravine
#

^

slate swan
#

where would i put it though srry been a while since i used embeds

sudden moss
#
@bot.event
async def on_member_join(member):
   await
embed = discord.Embed(description=f"Welcome **{member.mention}**") bot.get_channel(891878891889766414).send(embed=embed)```
#

@slate swan

slate swan
#

ty

boreal ravine
#

wtf

#

bruh

sudden moss
slate swan
#

ahh gotcha

#

appreciate it boss

sudden moss
#

No problem

boreal ravine
#

just send it like a normal embed

#

😐

sudden moss
#

What he said

boreal ravine
#

!d discord.TextChannel.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**.
slate swan
#

two greens fighting huh

sudden moss
slate swan
#

πŸ˜„

#

I need some help tho, can any1 help me?

sudden moss
#

Yea sure

slate swan
sudden moss
#

did you install it yet?

slate swan
#

yes

sudden moss
#

oh

boreal ravine
sudden moss
#

At the top of your code

slate swan
#

no no that's not what I meant

sudden moss
#

Then?

slate swan
#

Like, how can I import discord.py and see the files in it

sudden moss
#

It's on GitHub

slate swan
boreal ravine
#

literally every discord api lib

#

is open source

slate swan
#

Oh can u guys send me the link in github?

sudden moss
#

I'd recommend using py-cord anyways it's mantained at least

sudden moss
boreal ravine
sudden moss
#

He was faster

slate swan
#

Ty

reef shell
#

There are many discord api wrapper library written in JS

#

Lmao

slate swan
#

For Python?

reef shell
#

Bruh?

#

Pepega

boreal ravine
reef shell
#

how dumb question

slate swan
#

so one more question and I'll proceed with my code, I wan't to make a fully functional and SAFE eval command, is there any tutorial for it?

sudden moss
#

Yeah

reef shell
#

Python is a language, so is JS

sudden moss
valid perch
#

use jishaku or snekbox

#

snekbox for fully safe, jissaku for easy

slate swan
#

could u send the docs to snekbox

reef shell
#

jishaku is the easiest and widely used

valid perch
slate swan
#

hmm, what does it do tho, eval(arg) isn't enough?

valid perch
#

snekbox requires actual effort since its containerized evaluation etc

slate swan
#

like I want to do a command like this one

#

!e print("hello")

unkempt canyonBOT
#

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

hello
slate swan
#

yeah, we use snekbox

#

!src eval

unkempt canyonBOT
#
Command: eval

Run Python code and get the results.

Source Code
slate swan
#

oh ok ty

#

daaaaang that's alot of code

valid perch
#

You asked for safe lel

#

use jishaku tbh, likely enough for your needs if its only eval for your usage

slate swan
#
    async def post_eval(self, code: str) -> dict:
        """Send a POST request to the Snekbox API to evaluate code and return the results."""
        url = URLs.snekbox_eval_api
        data = {"input": code}
        async with self.bot.http_session.post(url, json=data, raise_for_status=True) as resp:
            return await resp.json()
``` this is the main part of the code
#

you just send a post result to snekbox and get the output back

#

the rest of the code manages revaluates, output formatting and stuff

#

So, how come there is a unsafe eval and a safe eval, I haven't understood that yet

#

well if you're using eval(code), you're running that code on your machine

#

that is equivalent to letting someone type some code on your computer and running it

#

so I could basically hack the owner of Python Bot if it wasn't safe?

visual island
#

it is hosted in some hosting service, so no

#

if the bot runs on the owner's computer then yes

slate swan
#

daaang, so I have to make the command so only I can run it right

#

yeah, if you're planning on going the eval(code) way

#

(fwiw, we do go the eval(code) way for internal eval commands that only admins can use)

#

mhm okay i get it, so snekbox is another way of doing eval() right

#

this is a safe one right?

valid perch
#

Would be my recommendation

sudden moss
slate swan
#

!e x = input(">>> ")

unkempt canyonBOT
#

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

001 | >>> Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | EOFError: EOF when reading a line
slate swan
#

why wont eval let me take inputs?

boreal ravine
#

bro

#

this eval command isnt a console

visual island
#

input goes to sys.stdin

#

and discord isn't stdin

#

or other name "console"

slate swan
#

ok ok sry im trying to learn

#

!resources

unkempt canyonBOT
#
Resources

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

maiden fable
slate swan
#

I'm trying to build the eval code from scratch now but it doesn't work,

from discord.ext import commands


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

    @commands.command(hidden=True)
    @commands.is_owner()
    async def eval(self, ctx, *, args):
        await ctx.send(exec(args))


def setup(client):
    client.add_cog(Command(client))
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message
maiden fable
#

Wyn

#

@bot.listen()

visual island
#

sys.stdin = message in on_message event

maiden fable
#

Hmm

visual island
#

actually, you need to write it in a file

maiden fable
#

Good idea

visual island
#

or no idk

maiden fable
#

Wait, sys.stdin should be message.channel

visual island
#

never tried that

maiden fable
visual island
maiden fable
#

StringIO*

#

That's what I use for my eval command

visual island
maiden fable
#

Anyways who knows how to do that

visual island
#

let me try with my bot

valid perch
#

sys.stdin = m.content..?

#

Tis an object with more then 1 value after all

visual island
valid perch
#

Well your making it a message object atm

visual island
#

thinking of

    sys.stdin.write(m.content)
io.UnsupportedOperation: not writable
```this
valid perch
#

You can mocks stdin

#

Possibly using StringIO

visual island
#

TypeError: write() argument must be str, not _io.StringIO

#

i provided a string before bruh

#

python's confusing

valid perch
#

Not writing to it, mocking it

#

sys.stdin = io.StringIO('asdlkj')

visual island
#

ohh

valid perch
#

Then you can write to it

visual island
#

wait

valid perch
#

But hey πŸ€·β€β™‚οΈ

#

It's just an in memory buffer

visual island
#

it doesn't do anything

#

hmm

valid perch
#

What doesnt do anything

visual island
#
@bot.event
async def on_message(m):
    import sys
    import io
    sys.stdin = io.StringIO(m.content)
    sys.stdin.write(m.content)
    print(sys.stdin.getvalue())

```so apparently this works...
#

but what should I do with it...

valid perch
#

Whatever you want

#

Issue is stdin is one stream, while each discord channel can in theory be its own

#

At which point, given sequential program execution theres no point

#

imo

visual island
manic wing
#

yeah I love importing stuff in functions

#

normally i like

#

i do py import os print(os) if os: import os if __name__ == "__main__": import os def x(): ... x() import typing from typing import * main() from tkinter import * if tk.os: from tkinter import * from tkinter import tk import discord import discord.ext from discord import ext

#

this my favourite

#

i also just stick from tkinter import * in random places

#

why not, right?

boreal ravine
#

why do you need it twice

manic wing
#

omg

slate swan
#
    async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, str]] = None):
        embed = discord.Embed()
        embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
        embed.set_footer(text=f"Information requested by: {ctx.author} ({ctx.author.id})",
                         icon_url=ctx.author.avatar_url)

        if arg == discord.User:
            embed.add_field(name=f"{arg.name}", value=f"empty")
            embed.colour = 0x6495ED
            return await ctx.send(embed=embed)
        elif not arg:
            embed.add_field(name=f"{ctx.author.name}", value=f"empty")
            embed.colour = 0x6495ED
            return await ctx.send(embed=embed)
        elif arg == "server" or arg == "guild":
            embed.add_field(name=f"{ctx.guild.name}", value=f"empty")
            embed.colour = 0x6495ED
            return await ctx.send(embed=embed)
        else:
            embed.add_field(name=f"a", value=f"a")
            embed.colour = 0xFF6347
            return await ctx.send(embed=embed)

How come when I mention a user like -info @slate swan it runs the else statement and not the first if statement?

marble pilot
#
    @commands.command()
    @commands.has_role("Admin")
    async def add(self, ctx, member:discord.Member, role:discord.Role):
        if member is None:
            task_embed = discord.Embed(title=":white_check_mark: Success!", description=f"Successfully added {role.name} to {ctx.author}", timestamp=ctx.message.created_at)
            await ctx.author.add_roles(role)
            await ctx.send(embed=task_embed)

Why when I live empty the member arg, i get the error:
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "<@&896699994483064952>" not found.

slate swan
#

Just type hint it to a discord user

#

Then you can do -info @mention/id/name

slate swan
slate swan
#

arg == discord.User is like doing py 'apple' == str

#

oh, okay how can I use type or isinstance in this case?

#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#

so if isinstance(arg, discord.User)

#

sure

#

u sure that will work tho because it doesn't make sense to me

valid perch
#

Try it and see

#

isinstance will look at arg and return true if its of type discord.User

limpid thicket
#

What's the unstable API reference called again?

boreal ravine
slate swan
#

btw, set_image isn't working

#
            embed.set_image(ctx.author.avatar_url)

limpid thicket
#

I thought it was called master. Yes thank you.

boreal ravine
valid perch
#

You should be setting icon_url iirc

slate swan
#

the latest one

boreal ravine
boreal ravine
slate swan
#

idk

slate swan
#

in the docs it says set_image(*, url)

valid perch
#

url is a keyword argument

boreal ravine
boreal ravine
valid perch
#

Therefore url=...

slate swan
#

oh ok ty

#

ctx.author.created_at will return the users created at information right?

boreal ravine
#

yes

slate swan
#

but author is a member?

valid perch
#

*, .. denotes a keyword argument, they can only be set using there name

boreal ravine
valid perch
#

Author is a member if the message is in a guild

#

*command

boreal ravine
#

author is a discord.Member object and .created_at() is a datetime.datetime object

boreal ravine
slate swan
#

@valid perch isinstance wont work btw

valid perch
#

Whys that?

boreal ravine
slate swan
#
        if isinstance(arg, discord.User):
            embed.add_field(name=f"{arg.name}", value=f"empty")
            embed.colour = 0x6495ED
            return await ctx.send(embed=embed)
#

instead of returning this, it returns the else statement

boreal ravine
slate swan
#
arg: typing.Optional[typing.Union[discord.User, str]] = None
valid perch
#

Thats a typehint, besides it can be optional

#

print(arg, type(arg)) for me

#

I'd like to see why isinstance doesnt work : )

slate swan
#
Misa#2635 <class 'discord.user.ClientUser'>
boreal ravine
#

is that a bot

valid perch
#

Theres your issue then, its not User so isinstance won't return true

slate swan
#

ya

slate swan
#

oh can any1 of u guys join my server? i have to try it on a user then

valid perch
#

Try it on yourself

slate swan
#

how?

#

if i just do -info it will return my info

valid perch
#

The same way you'd try it on us?

slate swan
#

but it will return my info no matter what

valid perch
#

So why would us joining matter

slate swan
#

Just do the command with yourself as argument

#

oh nvm it worked on myself

#

You can see if it works

#

How would I ignore this error so it doesnt appear in console?
TypeError: 'NoneType' object is not subscriptable This is turning up because the value isnt present in the databse

valid perch
#

Check if iits none before you try use it and return

placid skiff
#

Or in your on_error event check if the error is an instace of TypeError and just pass it

slate swan
# valid perch Check if iits none before you try use it and return
    @commands.Cog.listener()
    async def on_message(self,message):
        if message.author.bot:
            return
        for x in message.mentions:
            print(f'{x.id} has been mentioned')
            uid = await self.coll.find_one({"user_id": str(x.id)}) #getting the user ID if in db then getting reaction
            
            reaction1 = uid["reaction"]
            await message.add_reaction(reaction1)

This is my code would something like if uid == None: return work?

placid skiff
#

Yes

valid perch
#
if not uid:
  return
slate swan
slate swan
slate swan
#

So when I use inline=True on my embeds, its always 3 fields next to each other but i want 2, otherwise everything is compact

#

how do I do that

#

dont think thats possible

maiden fable
slate swan
#

you can use empty field name and value for the third field
and let the third field be 4th one

#

hmm okay, well how do I shorten the created_at and the joined_at date

#

strftime function

#

strftime function?

#

!strftme

#

!strftime

#

well , you can format datetime's data using strftime

#

example code pls?

#

!d datetime.date.strftime

unkempt canyonBOT
#

date.strftime(format)```
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
slate swan
#

yes but could u give a example using either created_at or joined_at

#

!e py import datetime print(datetime.datetime.now().strftime("%#d %B %Y"))

unkempt canyonBOT
#

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

22 October 2021
slate swan
#

^

#

how can i turn the month into number?

#

replace B with m

#

ok ty

#

How do I display the date a member's account was created in an embed?

#

<user>.created_at

round forum
#

Guys

#

Does anyone have a god discord bot?

slate swan
#

python discord has one -> @unkempt canyon

slate swan
slate swan
round forum
slate swan
#

I assume they want it on the bottom left, timestamp

#

hm

slate swan
#

let them decide what they want to do with it. we've already given sufficient answers

#

correct

#

!d discord.Member.created_at is that they want , where to use it is thier decision

#

Β―_(ツ)_/Β―

maiden fable
#

pithink a large discussion on such a small topic...?

slate swan
#

πŸ«‚ exactly

#

Where in the docs can I find how to set a activity for my client?

#

I couldn't find it

maiden fable
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter.
maiden fable
#

!d discord.Client.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
The activity being used upon logging in.
maiden fable
#

!d discord.Client.status

unkempt canyonBOT
#

property status```
[`Status`](https://discordpy.readthedocs.io/en/master/api.html#discord.Status "discord.Status"): The status being used upon logging on to Discord.
slate swan
#

Thanks

#

but it doesn't work

#
from discord.ext import commands


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

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"Started client as: {self.client.user}")
        self.client.change_presence(activity="-help")


def setup(client):
    client.add_cog(Event(client))
hasty iron
#

it returns a coroutine

slate swan
#

wdym

lament mesa
slate swan
#

And you shouldn't change the presence in the on_ready event, not good

#

oh ok ty

#

why?

#

You can just set an activity kwarg to your bot constructor

#

bot constructor?

#

Yes

lament mesa
slate swan
#

I do it everywhere?

#

When initializing commands.Bot

#

You only initialize it once....

#

idk what initialize mean

lament mesa
#

foo = Foo()

slate swan
#

Have you learned Python before doing a bot

#

It's literally initializing a variable

heavy folio
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/entrance.py", line 12, in on_message
    mod_role = message.guild.get_role(886053029760106516)
AttributeError: 'NoneType' object has no attribute 'get_role'
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/entrance.py", line 17, in on_message
    if mod_role in message.author.roles:
AttributeError: 'User' object has no attribute 'roles'
```got this error, code: ```py
    @commands.Cog.listener()
    async def on_message(self, message):
        mod_role = message.guild.get_role(886053029760106516)
        if message.channel.id == 890543918964432906:
            if message.author.id == self.bot.user.id:
                return
            elif message.content not in ('des v', 'des ver', 'des agree'):
                if mod_role in message.author.roles:
                    return
                else:
                    return
```not using replit btw, its some sort of host just cant open vsc rn
how come i cant `get_role`? the role id exists
lament mesa
#

The message was sent in a dm

maiden fable
slate swan
#

i only know the smiple/basic python

#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

What's the difference between discord.Member.activites and discord.Member.activity

#

I didn't understand it

hasty iron
#

one is plural the other is singular

slate swan
#

omg no like, what is the difference of what they return

dapper trail
#

hey i broke my bot

#

;-;

#

i added the ping user command so that whenever someone pings the bot the bot will give the prefix back

#

but now any other command dont work

#
async def on_message(message):
    mention = f'<@!{bot.user.id}>'
    if mention in message.content:
        await message.channel.send("My prefix is g \n Ya can type g help for more info")```
#

this is the code

#

can anyone help?

hasty iron
slate swan
#

I'm trying to do cogs but I am getting errors

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

FileNotFoundError: [WinError 3] The system cannot find the path specified: '/cogs/economy'

slate swan
#

well yeah ik that but i have no clue on how to fix it

hasty iron
#

try relative path

manic wing
#

you might mean ./cogs

slate swan
#

Ok

manic wing
#

normally it helps if you specify a path that exists, but each to their own

slate swan
#

Now it thinks that cogs is file?

discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.bal' could not be loaded.
slate swan
slate swan
manic wing
#

send the file

slate swan
slate swan
# manic wing send the file

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

    @commands.command(aliases=["bal"])
    async def balance(self,ctx):
        
        bal_em = discord.Embed(title = f"{self.ctx.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
        await ctx.send(bal_em)

def setup(bot):
    bot.add_cog(BalCog(bot))
manic wing
#

send the traceback, maybe you missed imports and whatnot

slate swan
slate swan
# manic wing send the traceback, maybe you missed imports and whatnot

Ok

Traceback (most recent call last):
  File "c:\Users\leogr\OneDrive\Desktop\robojackle2\main.py", line 17, in <module>
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\leogr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 676, in load_extension
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.bal' could not be loaded.
slate swan
#

you have to import commands

#

then send the whole code in your file

#
import discord
from discord.ext import commands

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

    @commands.command(aliases=["bal"])
    async def balance(self,ctx):
        
        bal_em = discord.Embed(title = f"{self.ctx.name}'s Balance", description = f"You have a balance of",colour=0xFFA500)
        await ctx.send(bal_em)

def setup(bot):
    bot.add_cog(BalCog(bot))
#

hmm let me see your whole main file, remove the token tho

#

Ok

import discord
from discord.ext import commands
from discord import Intents
import json
import asyncio
import os
import pymongo

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

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

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

@bot.event
async def on_ready():
    print(bot.user.name + " is online.")

bot.run("token")
hasty iron
#

oh actually

slate swan
#

It is

hasty iron
#

its extension not found

#

hm

#

oh you're listing cogs.economy but loading cogs

#

you have to do cogs.economy.*

#

in load_extension

slate swan
#

Oh ok

#

That worked

#

Thanks

#
@commands.command()
    async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.ClientUser, str]] = None):
        if isinstance(arg, discord.User):
            platform = ""
            if arg.is_on_mobile():
                platform = "Mobile"

why does arg.is_on_mobile() not work? i tried arg.user.is_on_mobile() too

hasty iron
#

why are you typehinting as ClientUser

slate swan
hasty iron
#

why?

slate swan
#

doesn't matter why in this issue

hasty iron
#

ClientUser is a class used by bot.user

slate swan
#

yes

hasty iron
#

you cant use it like that

slate swan
#

but im not checking for clientuser atm

hasty iron
#

how about you show us the error you get

slate swan
#

its saying arg doesn't have a method called is_on_mobile()

#

arg should return discord.User in this case

hasty iron
#

ok

#

it doesnt have that attribute

slate swan
#

So how do I solve it?

hasty iron
#

is_on_mobile is only for Member

slate swan
#

hmm I see

#

but arg.member wont work right

#

so how would I do now?

manic wing
#

typehint to discord.Member

hasty iron
#

yeah User cant magically turn into Member by doing User.member

slate swan
#

so I can use two type hints in the isinstance()?

hasty iron
#

it can take in a tuple of types

#

as second arg

slate swan
#

hm I see

#

one more question

#

discord.User will be if arg is a mention, would discord.Member also be a mention?

manic wing
#

yes

hasty iron
#

yes, mention, name or id

#

all of those work

slate swan
#

ok nice thanks man

#

So in this case the solution is:

if isinstance(arg, discord.User) or isinstance(arg, discord.Member):
``` right?
#

but would both be True?

hasty iron
#

if isinstance(arg, (discord.User, discord.Member))

slate swan
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'member'
#

I dont get it

manic wing
#

you cant do User.member

slate swan
#
    async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None):
        embed = discord.Embed()
        embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
        embed.set_footer(text=f"Information requested by: {ctx.author} ({ctx.author.id})",
                         icon_url=ctx.author.avatar_url)

        if isinstance(arg, (discord.User, discord.Member)):
            platform = ""
            if arg.member.is_on_mobile():
                platform = "Mobile"
            elif not arg.member.is_on_mobile():
                platform = "Computer"

            embed.add_field(name="Name:", value=f"{arg.member}", inline=True)
            embed.add_field(name="Nick:", value=f"{arg.member.nick}", inline=True)
            embed.add_field(name="ID:", value=f"{arg.user.id}", inline=True)
            embed.add_field(name="Created:", value=f"{arg.user.created_at.strftime('%Y-%m-%#d')}", inline=True)
            embed.add_field(name="Joined:", value=f"{arg.member.joined_at.strftime('%Y-%m-%#d')}", inline=True)
            embed.add_field(name="Activity:", value=f"{arg.member.activity}", inline=True)
            embed.add_field(name="Status:", value=f"{arg.member.status}", inline=True)
            embed.add_field(name="Platform", value=f"{platform}")
            embed.add_field(name="Top Role:", value=f"{arg.member.top_role}", inline=True)
            embed.add_field(name="Roles:", value=f"{arg.member.roles}", inline=True)
            embed.add_field(name="Perms:", value=f"{arg.member.guild_permissions}", inline=True)
            embed.add_field(name="worked", value="worked")
            embed.set_thumbnail(url=arg.member.avatar_url)
            embed.colour = 0x6495ED
            return await ctx.send(embed=embed)
#

yes ik but we did discord.Member tho?

hasty iron
#

what?

slate swan
#

async def info(self, ctx, arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None):

hasty iron
#

ok so what

slate swan
#

if isinstance(arg, (discord.User, discord.Member)):

hasty iron
#

both dont have the member attr

slate swan
#

but I need to access both of them?

hasty iron
#

?

slate swan
#

both user and member

hasty iron
#

is_on_mobile is only for Member

slate swan
#

yes

hasty iron
#

ok and you're checking for both User and Member

#

also, you should do Union[Member, User, ...]

slate swan
#

why what's the difference if u dont mind explaining

hasty iron
#

User converter will never fail

#

because it calls the API if the user isn't cached

#

and if the one ur targeting is someone in the same guild it will convert it to User since the target is cached

#

well hopefully that makes sense

slate swan
#
arg: typing.Optional[typing.Union[discord.User, discord.Member, discord.ClientUser, str]] = None

should be:

arg: typing.Optional[typing.Union[User, Member, ClientUser, str]] = None

is what you mean?

hasty iron
#

no?

#

there is no difference there

#

did you read what i said

slate swan
hasty iron
slate swan
#

yes I did but i'm not experienced enough to fix this issue, I understood it tho

#

that's why I'm asking for help

hasty iron
#

so making Member first in the Union requires experience?

#

its literally just moving it

slate swan
#

So you meant, that I change from discord.User to discord.Member first?

hasty iron
#

yes

slate swan
#

Ohhh

#

But wouldn't the same thing happen with discord.Member?

hasty iron
#

?

slate swan
hasty iron
#

you still dont get the point

#

Member will fail if the user is not inside the guild

#

User will never fail

#

unless the api failed to get the user (if it isnt cached)

slate swan
#

Ohhh okay thank you

#

btw my bot is fucked

#

i think I ran the bot twice

#

And I only have access to one terminal to close it, idk how to access the other one to close the second

inner geyser
slate swan
#

Ok Thanks

vale narwhal
#

How do i check if user got specific role added on on_member_update event?

hasty iron
#

compare before.roles with after.roles

velvet tinsel
#

How do you make a bot do something when it is pinged?

#

😦

hasty iron
#

!d discord.ClientUser.mentioned_in

unkempt canyonBOT
velvet tinsel
#

Is it a client.event?

hasty iron
#

its a method

velvet tinsel
#

Ok

slate swan
#

When I try to get the channel ID, I get a statement like this.
Please tell me how to get just the id part of this statement.

slate swan
#

not the id of it

#

ctx.channel.id

#

is probably what you'd want

velvet tinsel
#

Is there a client.send_message?

#

Or do I have to use ctx?

slate swan
#

because then you just have to get the user

#

and do

#

await user.send("msg")

#

like if this is an on_message

#

which i think it is

#

you'd do, await message.author.send("msg")

velvet tinsel
slate swan
#

yeah

velvet tinsel
#

Ok

slate swan
#

except no

velvet tinsel
#

So I write await user.send(β€œmsg”)?

slate swan
#
if message.content.lower().startswith("bob"):
  await message.channel.send("msg")
velvet tinsel
slate swan
#

i'm pretty sure

velvet tinsel
#

Thanks

slate swan
#

ofc

#

Hello i need help
How can i make like a slowmod if i make an command
like:
!beg
[command]

!beg
[Please wait 30m until the command]

maiden fable
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.
velvet tinsel
#

I have a bot I added to a server, but it doesnt respond to the commands i give it. What’s happening?

slate swan
maiden fable
velvet tinsel
#

Yes

maiden fable
#

And u r using @bot.event deco?

velvet tinsel
#

Nope

maiden fable
#

Huh

velvet tinsel
#

Client.event

maiden fable
#

Ah yea that only

#

(Don't name your commands.Bot instance client please)

#

Just exchange it with @client.listen()

#

And it's gonna work

velvet tinsel
#
from discord.ext import commands
import random

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

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(client.latency*1000)}ms')

@client.event
async def on_ready():
    print("Bot is ready.")


@client.command()
async def fate(ctx, member1, member2):
    responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
                 " will hate ", " will become friends with ", " will betray "]
    await ctx.send(f'{member1} {random.choice(responses)} {member2}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]

    if message.content.lower().startswith("tianzheng"):
        await message.channel.send(random.choice(resp))
#

here

#

the commands aren't working is what I'm saying

maiden fable
#

Ik...

#

As I said, exchange @client.event with @client.listen()

velvet tinsel
#

py client.listen()

#

ok

#

Still not responding

maiden fable
#

Code

velvet tinsel
#

πŸ˜›

#

Uh

#

Ok

#
from discord.ext import commands
import random

bot = commands.Bot(command_prefix="&")

@bot.listen()
async def ping(ctx):
    await ctx.send(f'Pong! {round(bot.latency*1000)}ms')

@bot.event
async def on_ready():
    print("Bot is ready.")


@bot.listen()
async def fate(ctx, member1, member2):
    responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
                 " will hate ", " will become friends with ", " will betray "]
    await ctx.send(f'{member1} {random.choice(responses)} {member2}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]

    if message.content.lower().startswith("tianzheng"):
        await message.channel.send(random.choice(resp))
maiden fable
#

Bro

velvet tinsel
#

What

maiden fable
#

I said to replace event decos, not commands

velvet tinsel
#

Ok

#

Uhhh

#

It’s working, but there is a problem where it just says ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: command β€˜ping’ is not found

#

Weird

velvet tinsel
maiden fable
boreal ravine
velvet tinsel
boreal ravine
velvet tinsel
#

Because @maiden fable told me to

maiden fable
boreal ravine
#

don't use things if you don't know what it does

boreal ravine
velvet tinsel
#

Ok

boreal ravine
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

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

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

Example...
boreal ravine
maiden fable
#

Nvm forgot client doesn't have commands

velvet tinsel
#

Still not working

#
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found
boreal ravine
#

your using .listen() for your ping command

velvet tinsel
#

Now it’s not listening again

#

It’s not responding

boreal ravine
velvet tinsel
#

There is no error

slate swan
#

Please tell me how to send an embed and a regular message together.

velvet tinsel
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

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

what can i add in serverinfo command?

reef shell
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.
boreal ravine
#

^

velvet tinsel
#
from discord.ext import commands
import random

bot = commands.Bot(command_prefix="&")

@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round(bot.latency*1000)}ms')

@bot.event
async def on_ready():
    print("Bot is ready.")


@bot.command()
async def fate(ctx, member1, member2):
    responses = [" will marry ", " will fall in love with ", " will kill ", "will have a fight with ", " will argue with ",
                 " will hate ", " will become friends with ", " will betray "]
    await ctx.send(f'{member1} {random.choice(responses)} {member2}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    resp = ["I hope you're feeling ok!", "OK", "it's fine", "download python now btw", "If you need help call childline"]

    if message.content.lower().startswith("tianzheng"):
        await message.channel.send(random.choice(resp))
slim whale
reef shell
#

And methods

#

That is enough to give you ideas

slim whale
#

okkk

velvet tinsel
#

yes

boreal ravine
velvet tinsel
#

It works

#

The on_message works, but the ping doesnt

boreal ravine
#

im using put .listen() on your on_message event

velvet tinsel
#

Ok

boreal ravine
#

it searches every message

#

so it doesn't respond to the command

velvet tinsel
#

Thanks it works now

boreal ravine
#

πŸ‘

ocean leaf
#

i used pip install -U git+https://github.com/Rapptz/discord.py command to install discord.py but it installed another version

#

i wanted to install 2.0

#

it installed 1.7.3

#

how to install 2.0 in replit?

reef shell
#

^

lament mesa
slate swan
slate swan
#

I created a channel with on_member_join. I want to set permissions for the channel, but I don't know how to get the channel id that I created. Can someone please tell me how to do this?

reef shell
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a β€˜secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
reef shell
#

This returns the created channel object

slate swan
reef shell
#

and channel obj. has an id attribute

reef shell
#

It'll take you to that page

slate swan
#

Hello i need help
How can i make like a slowmod if i make an command
like:
!beg
[command]

!beg
[Please wait 30m until the command]

slate swan
#

invalid character from identifier

slim whale
#

c= len([c for c in ctx.guild.TextChannels]) is this correct? i want the number of text channels

#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: 'Guild' object has no attribute 'TextChannels'

#

it would be ctx.guild_TextChannels?

slate swan
#

!d discord.Guild.text_channels

unkempt canyonBOT
#

property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
boreal ravine
slim whale
clear rapids
#
@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
      await message.channel.send("don't disturb me I have work to do just type ***'$help'*** and help yourself")       ```                          I am using this command to send a message when someone tags the bot , but for some reason this command is blocking all the rest of my commands
#

is there any other way to do this using ctx?

ocean leaf
slate swan
unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
slate swan
#

add this coro to the end of you code , or use .listen() instead of an event

clear rapids
slate swan
zinc mural
#

can somebody help me ?

slim whale
#

guild.news_channel @reef shell how is this?

clear rapids
slate swan
#

i said end , or start
not above it

slim whale
#

or how?

slate swan
#

also , you weren't asked to exactly copy and paste it

reef shell
#

what do you want to do exactly

clear rapids
slim whale
clear rapids
reef shell
barren isle
#

What is wrong here? Ive been trying to find the error for a while

slim whale
slate swan
#

Hey how can I mention all roles name in the guild without all those long ass text? I tried ctx.guild.roles but it gave me a long ass list with IDs and idk what

reef shell
#

!d discord.TextChannel.is_news

unkempt canyonBOT
#

is_news()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is a news channel.
slim whale
#

tnx

reef shell
# unkempt canyon

So you can iterate through the TextChannels and get your desired news channel by checking this

barren isle
rough flicker
#

anyone know how to get these two things working?

#
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='?')

class Dms(commands.Cog):
  def __init__(self, bot:commands.Bot):
    self.client = bot
    
  @bot.event
  async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!')

def setup(bot: commands.Bot):
  bot.add_cog(Dms(bot))
#
class Anti(commands.Cog):
  def __init__(self, bot:commands.Bot):
    self.client = bot
  
  @commands.Cog.listener()
  async def on_message(self, message: discord.Message):
    if message.content.startswith(f"{self.bot.user.id} or {self.bot.user.mention}"):
        await message.channel.send(random.choice(responses))
    elif message.author == self.bot.user:
      return
slate swan
clear rapids
slate swan
#

cool

slate swan
reef shell
slate swan
#
[<Role id=900109488609189958 name='@everyone'>, <Role id=900109858139959409 name='Misa'>]
#

how can I just get the role names?

rough flicker
#

oh okay

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...
slate swan