#discord-bots

1 messages · Page 478 of 1

slate swan
#

What's the best way to ban a member based solely off their ID#

wicked atlas
slate swan
#

Thank you bud!

#

really appreciate that!

lyric moat
#

why it says this when i am trying to join a voice channel

slate swan
#

!PyPi pynacl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

slate swan
lyric moat
#

did i misspell or? py @client.command() async def leave(ctx): voiceture = ctx.author.voice mevoiceture = ctx.guild.me.voice if voiceture is None: return await ctx.send('Your are not currently in a Voice Channel !') if mevoiceture is None: return await ctx.send('I am not currently in a Voice Channel') await ctx.voice_client.disconnect() await ctx.send('I have Successfully Left Your Voice Channel ! ')

vale pendant
#

it's author instead of authour

trim barn
#

AttributeError: 'NoneType' object has no attribute 'get_role'

# Insert all important variables into this class.
class variables:
...
    db = cluster["EasyBallot"]  # Insert DB name
    vote_db = db["Discord Election Votes"] # Insert collection name
    guild_id = client.get_guild(880888575175036998) # Insert the guild id of the server your bot will be active in.
    vote_registered_role = guild_id.get_role(880888727218556949) # Insert guild id and role id of registration role (if applicable)
#

help please

#

I am trying to make a global variable in the sense that I am making a class in the main bot file and importing it to the cogs to use as variables so it's easy to tweak the data

#

but for some reason vote_registered_role only functions as a local variable

#

and it's getting messy so I am attempting to store it all in one class

visual island
trim barn
#

well, yeah, that.

#

i just need it to be used in more than one file, so i made it a class and important the class to cogs to use the variables

#

i think you get the gist, but I keep having this error yet for some reason this would function normally as a local variable

visual island
#

the guild ID is probably wrong?

trim barn
#

nope i've tried it and tested it

#

it's not wrong but I can retry

cyan sundial
#

ill host for u but u probably dont trust me

trim barn
#

buy an old computer and shove an SSD into it and install linux on it

cyan sundial
#

why an ssd

trim barn
#

old computers run like shit

cyan sundial
#

lol

#

i have old computer

trim barn
#

unless you're trying to store a lot of things go for an ssd

cyan sundial
#

i have 400gb storage and 16gb of ram on my vps

#

its pretty quick

#

i host like some random 30 something things on it

trim barn
#

not overspending on vps?

cyan sundial
#

nope

#

its only around 20 a month and someone else pays it for me

trim barn
#

i used digitalocean but didn't feel like paying further lol since i was living off github education anyways

cyan sundial
#

actualy its 14 a month

trim barn
cyan sundial
#

does anyone know how i can do owner only commands with like if the author is not in the owner ids list it ends, but if it is it will continue

cyan sundial
#

i need more then 1 owner

#

without a team

trim barn
#

create a check

#

or manually create a list and make an if statement that verifies

cyan sundial
#

thats what im trying to do but how do i check if its in the list?

trim barn
#

print statements are always safe ways to check if things are working properly

cyan sundial
#

ill just have a list of owner ids at the top of the file like py OWNER-IDs = ["1231231231", "23123123123"]

trim barn
#

the uppercase is pissing me off

cyan sundial
#

lol

trim barn
#

and i'd use underscores

#

as a divider

cyan sundial
#

i will

#

i just made that real quick

#

how do i check thru a list?

trim barn
#
for x in owner_ids:
  print(x)
cyan sundial
slate swan
#

alright then

cyan sundial
slate swan
trim barn
cyan sundial
#

i want if the authors id is in the owner ids then it will send that they dont have permision
(i can send the non perms message)

trim barn
#
if ctx.author.id in owner_ids:
  # do something
slate swan
cyan sundial
#

i just dont know how to check the list for the authors id

boreal ravine
#

if id:
send message

boreal ravine
trim barn
cyan sundial
slate swan
trim barn
#

yes

slate swan
unkempt canyonBOT
#

discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
cyan sundial
#

i am not owner of the bot

trim barn
#

has all permissions too

cyan sundial
#

did u even read my message

slate swan
slate swan
#

read the second reply

cyan sundial
slate swan
#

add your id in the list

cyan sundial
#

ok

trim barn
#

@slate swan do you know anything else that may be the issue

slate swan
#

File "/usr/lib/python3.8/json/init.py", line 106, in <module>
from .decoder import JSONDecoder, JSONDecodeError
File "/usr/lib/python3.8/json/decoder.py", line 3, in <module>
import re
File "/usr/lib/python3.8/re.py", line 145, in <module>
class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
exit status 1

slate swan
trim barn
#

that defeats the purpose of what I am trying to do

slate swan
trim barn
#

how would that work when I'm making the class so i have a universal way of storing variables that can be imported to another file

slate swan
trim barn
#

I'm aware but how would a function work when I'm only trying to store variables

slate swan
#

you are trying to fetch only the role from the class right?

trim barn
#

yes

#

but only so I can use it in another folder

#

for instance

#
        embed.add_field(name="Election Turnout",
                        value=f'{round(float(total_votes / len(self.vote_registered_role.members)) * 100, 2)}%',
                        inline=False)
slate swan
#
def function_for_role():
  role = #get the role 
  return role```
#

it returns the role whenever you call the func

trim barn
#

but how could I use it for what I described

#

@slate swan

cyan sundial
#

doing this should work right? py @client.command() async def isowner(ctx): if ctx.author.id in owner_ids: await ctx.send("you are a owner") else: await ctx.send("lol idiot isnt owner hA")
my owner ids is

owner_ids = ["401514800984621066", "555625169696194562"]```
#

it thinks im not owner

slate swan
#

just for importing?

slate swan
#

remove those quotes

cyan sundial
#

oh

trim barn
#

i'm trying to make it easier to configure

cyan sundial
#

that fixed it

graceful gulch
cyan sundial
#

i got it working

#

they were strings when they wernt suppost to be

slate swan
#

Is there a way to tell if a user Is online

maiden fable
unkempt canyonBOT
#

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

this works normally

#

in a local variable

maiden fable
#

Also please don't make them class vars

ocean leaf
#

Is there any module called discord_components?

trim barn
#

no

trim barn
maiden fable
ocean leaf
#

wait lemme restart

maiden fable
maiden fable
trim barn
#
# Insert all important variables into this class.
class variables:
    def __init__(self, client):
        self.guild_id = client.get_guild(880888575175036998) # Insert the guild id of the server your bot will be active in.
        
    cluster = MongoClient('x') # Insert MongoClient Key

    db = cluster["EasyBallot"]  # Insert DB name

    vote_db = db["Discord Election Votes"] # Insert collection name

    guild_id = client.get_guild(880888575175036998) # Insert the guild id of the server your bot will be active in.

    vote_registered_role = client.get_guild(880888575175036998).get_role(880888727218556949) # Insert guild id and role id of registration role (if applicable)
#

so like this?

maiden fable
#

I mean

#

Do u know about instance variables?

trim barn
#

bcause im running on 2.7 braincells atm

#

no im shit with classes

maiden fable
#

So what u were making before were class variables

#

They can be accessed via variables.db and stuff

#

But instance variables are accessed via variables().db

ocean leaf
maiden fable
#

So the self represents the class itself

#

I suggest you learn a bit more about class and instance variables and then continue this project of yours... @trim barn

#

!resources have some good tutorials on OOP (object oriented programming)

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.

trim barn
#

im gonna make a config.json instead

maiden fable
#

Your wish

zealous needle
#

how do I add a role to a user without the use of a command

maiden fable
#

Old syntax

zealous needle
#

nono

#

uh lemme elaborate

maiden fable
zealous needle
#

is message.author okay?

maiden fable
#

Sure

zealous needle
#

what is the function for adding roles and how do i use it?

maiden fable
unkempt canyonBOT
#

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

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

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

how can i get a discord.Role object from a role ID

valid galleon
#

is there a way to make a command which googles the term and returns the first link?

ocean leaf
#

is discord_components enough for making buttons or any other module is needed?

ocean leaf
red iris
#

i am confused

maiden fable
#

#bot-commands

red iris
ocean leaf
#

!e

while True:
  print('and again')
#

yeah

maiden fable
ocean leaf
maiden fable
#

Ah ok

ocean leaf
#

!e

for i in range(2):
  print('Hello, World!')
unkempt canyonBOT
#

@ocean leaf :white_check_mark: Your eval job has completed with return code 0.

001 | Hello, World!
002 | Hello, World!
ocean leaf
#

ok

#

i wonder how this bot was made

#

it is also a python interpetor

#

and also controls this entire server

maiden fable
#

@ocean leaf bro #bot-commands

maiden fable
unkempt canyonBOT
slate swan
#

hey guys, is there any way to specify the cog i wanna get the list of the bots commands from?

#

i forgor 💀

maiden fable
maiden fable
slate swan
#

i tried for command in get_cog("cogname").bot.commands() lol

maiden fable
#

Bro

slate swan
#

wat

maiden fable
#

get_cog().get_commands()

slate swan
#

ah

#

but i can iterate through them immediately, why not

maiden fable
#

....?

slate swan
#

this will return a list of the commands, so why shouldnt i iterate through all of them immediately

maiden fable
#

Bro, your message doesn't make sense...

slate swan
#

then what does that return

valid galleon
maiden fable
#

Sorry, idk

valid galleon
#

alright np

ocean leaf
ocean leaf
fleet axle
#

Hey, Can anyone help how can I add server acknowledgement in userinfo command

valid galleon
#

i'll check it out, thanks

zealous needle
#

how do i give a bot permission to dd roles to users

lofty mulch
#

What's the exact purpose of Discord.HTTPErequest?

fleet axle
#

@maiden fable I mean like the bot dyno when you type ?whois u will get Acknowledgement info like he is server moderator or server admin like this how can I add in my userinfo command what is the code?

lofty mulch
#

HTTPEexception*

fleet axle
#

In settings

maiden fable
lofty mulch
#

Thx, luv u

maiden fable
#

(:

fleet axle
lofty mulch
#

So, uh

spark estuary
#

help error

lofty mulch
#

How can I use quotes without breaking the string? 😔

#

I'm braindead on this one

lyric moat
#

why do i have to make it linkable to play the play command? ```py
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(url, download=False)
        url2 = info['formats'][0]['url']
        source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)```
fleet axle
#

I mean

lofty mulch
#

Like, it's a legit black square

lyric moat
fleet axle
#

like keep ` this symbol

lofty mulch
#

Lemme check

spark estuary
fleet axle
#

for black square

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)
spark estuary
hot cobalt
#

@spark estuary Could you show us your code, I can guess what you've done but seeing the code would help

lyric moat
#

would it not get taken down?

hot cobalt
#

I'd imagine you're using discord.Client rather than discord.ext.commands.Bot

spark estuary
hot cobalt
#

Then yes, that's the issue

zealous needle
#

how do i give a bot user permission to give roles to other users

fleet axle
#

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

#

may be

#

this can solve

slate swan
hot cobalt
#

You'll need to import commands from discord.ext if you want to use the command syntax. ```py
from discord.ext import commands

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

fleet axle
spark estuary
fleet axle
#

yep

hot cobalt
#

It'll fix the issue you're currently facing, though there may be more

#

So start with that, see what happens next

spark estuary
slate swan
#

requests is blocking , the urllib library blocks asynchronous code

#

You may use aiohttp , or reddit's api

lament mesa
#

!d str.split

unkempt canyonBOT
#

str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.

For example:
boreal ravine
#

so blurry

heavy folio
heavy folio
boreal ravine
#

Why. Did. You. Delete. The. Message.

heavy folio
#

i gave the wrong image

#

not that

boreal ravine
#

It's self explanatory

#

The image is "so blurry"

spark estuary
#

my bot command is not working can someone help me pls

boreal ravine
spark estuary
boreal ravine
#

ok.

boreal ravine
spark estuary
#

i mean i had errors before but solved it

#

now it doesnt work

boreal ravine
#

hm

slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

@spark estuary

spark estuary
#
@cL#4483ient.command()
async def meme(ctx):
  async with aiohttp.ClientSession() as cs:
   async with cs.get("https://www.reddit.com/r/memes.json") as r:
     memes=await r.json()
     embed=discord.Embed(
       colour=discord.colour.purple()
     )
     embed.set_image(url=memes['data']["children"][random.randint(0,25)]['data']["url"])
     embed.set_footer(text=f"Powered by r/memes!|meme requested by{ctx.author}")
     await ctx.send(embed=embed)```
spark estuary
slate swan
spark estuary
#

no wait

#

my bad

#

i didnt check cmd i got an error

slate swan
#

what was the error?

boreal ravine
#

bruh

#

u said there wasn't an error???

spark estuary
spark estuary
spark estuary
slate swan
#

copy and paste it here

spark estuary
#

we have logged in as turdboi 2.0#8133
Ignoring exception in command meme:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\hp\Pictures\Python\reddit.py", line 23, in meme
memes=await r.json()
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client_reqrep.py", line 1097, in json
raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.reddit.com/r/memes.json')

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

Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.reddit.com/r/memes.json')
Press any key to continue . . .

slate swan
#

it's an error..

spark estuary
#

yes....my bad.....how do i fix it tho

slate swan
#

!code

#

paste ur code like that

spark estuary
#

ok

#

import discord
import os
from datetime import datetime
import json
import requests
import randfacts
import pyjokes
import random
import praw
from discord.ext import commands
import aiohttp

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

@client.command()
async def meme(ctx):
  async with aiohttp.ClientSession() as cs:
   async with cs.get("https://www.reddit.com/r/memes.json") as r:
     memes=await r.json()
     embed=discord.Embed(
       colour=discord.colour.purple()
     )
     embed.set_image(url=memes['data']["children"][random.randint(0,25)]['data']["url"])
     embed.set_footer(text=f"Powered by r/memes!|meme requested by{ctx.author}")
     await ctx.send(embed=embed)
lofty mulch
#

from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.ErrorHandling' raised an error: TypeError: 'module' object is not callable

#

Ideas on this one? I've checked my code and I haven't miss-typed anything

slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

spark estuary
slate swan
#
await r.json(content_type=None)

try that

spark estuary
slate swan
lofty mulch
#

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

spark estuary
heavy radish
#

Hello. Where can I learn Python for discord BOTs?? I just completed the W3 Schools Python workshop

little ether
heavy radish
#

Hm

spark estuary
#

e have logged in as turdboi 2.0#8133
Ignoring exception in command meme:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\hp\Pictures\Python\reddit.py", line 23, in meme
memes=await r.json(content_type=None)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client_reqrep.py", line 1113, in json
return loads(stripped.decode(encoding))
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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

Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

heavy radish
spark estuary
#

new eeror @slate swan

boreal ravine
slate swan
spark estuary
#

right?

slate swan
#

No

#
memes=await r.json(content_type='text/html')
spark estuary
#

memes=await r.json(content_type='text/html')

spark estuary
lofty mulch
#

18

heavy island
slate swan
#

take a look at it

#

I think you can figure it out

lofty mulch
#

o

#

welp

#

Thanks for the help

slate swan
#

still need help?

boreal ravine
lofty mulch
#

I think I figured it out, lemme see

slate swan
spark estuary
slate swan
#

What does import discord mean

boreal ravine
slate swan
slate swan
boreal ravine
#

No shitpost please

slate swan
lofty mulch
#

It totally flew over my head

slate swan
#

Nicee

lofty mulch
#

that I didn't add the listener

slate swan
#

Where do I get those import words

slate swan
#

How do u guys know what to type after the word import

#

google

lofty mulch
#

and not it accuses me of not having a listener???

boreal ravine
#

Modules

slate swan
lofty mulch
#

now*

slate swan
#

Ooo

#

So google

lofty mulch
#

go figure

boreal ravine
#

Yes

slate swan
#

@lofty mulch I think it's case_insensitive=False

#

I could copy free modules

little ether
lofty mulch
lofty mulch
#

It does?

slate swan
#

I could copy free modules from Google?

little ether
slate swan
lofty mulch
#

Well, today I learnt that class names make a difference

slate swan
spark estuary
slate swan
spark estuary
slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

lofty mulch
#

I was trying to execute the cog, wtf

slate swan
spark estuary
#
import discord
import os
from datetime import datetime
import json
import requests
import randfacts
import pyjokes
import random
import praw
from discord.ext import commands
import aiohttp

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

@client.command()
async def meme(ctx):
  async with aiohttp.ClientSession() as cs:
   async with cs.get("https://www.reddit.com/r/memes.json") as r:
     memes=await r.json(content_type='text/html')
     
     embed=discord.Embed(
       colour=discord.colour.purple()
     )
     embed.set_image(url=memes['data']["children"][random.randint(0,25)]['data']["url"])
     embed.set_footer(text=f"Powered by r/memes!|meme requested by{ctx.author}")
     await ctx.send(embed=embed)
     ```
#

Ignoring exception in command meme:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\hp\Pictures\Python\reddit.py", line 23, in meme
memes=await r.json(content_type='text/html')
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client_reqrep.py", line 1113, in json
return loads(stripped.decode(encoding))
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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

Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

lofty mulch
#

Trying to run the cog

#

Until I realized that I wasn't on my main file

slate swan
#

.

slate swan
#

!json

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

spark estuary
slate swan
lofty mulch
#

AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'

#

I'm starting to think that I should prob reread the documentation

#

Or I'm just spacing out too much

heavy island
valid perch
#

@commands.Cog.listener()

spring flax
#
@commands.Cog.listener()```
little ether
boreal ravine
spring flax
#

you do.

boreal ravine
#

you do?

spring flax
#

yes.

#

you do not need it for

@bot.event
lofty mulch
#

and I tried to run the cog again

boreal ravine
spark estuary
boreal ravine
#

it means you need

{
  "this": "thingy lol"
}
spark estuary
#

can i ping the helpers?

valid perch
#

Why?

spark estuary
#

becoz i need help

valid perch
#

With what?

spark estuary
#

my code

valid perch
#

Well, whats your code and whats the error

valid perch
#

Well, we have provided help.

#

Show your json file

spark estuary
#

i havent created any json file

quasi pawn
#

how is this done? Is there db involved?

valid perch
spark estuary
valid perch
#

Anyway lemme read code

#

Why are you setting content type?

heavy radish
#
import discord
from discord.ext import commands
from os import getenv
from dotenv import load_dotenv

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

@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))

@bot.command(name="hello")
async def hello_world(ctx: commands.Context):
    await ctx.send("Hello, world!")


load_dotenv() 
token = getenv("TOKEN")
spark estuary
heavy radish
#

What have I done wrong?

valid perch
slate swan
valid perch
heavy radish
#

noe

spark estuary
valid perch
valid perch
spark estuary
#

gnoring exception in command meme:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\hp\Pictures\Python\reddit.py", line 23, in meme
memes=await r.json()
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client_reqrep.py", line 1097, in json
raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.reddit.com/r/memes.json')

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

Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.reddit.com/r/memes.json')

slate swan
#

I know a way to fix all your troubles quick and easy

#

@spark estuary

spark estuary
#

yes...?

slate swan
#

just use a api

valid perch
#

Your url is invalid

#

Atleast, thats what its showing when I try go to it

heavy radish
spark estuary
#

this?

slate swan
valid perch
#

*The url in the error

slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

spark estuary
valid perch
#

Weiird

heavy radish
#

Anyone?

slate swan
#
r = requests.get(f"https://some-random-api.ml/meme").json()
image_url = r["image"]
@client.command()
async def meme(ctx):
  r = requests.get(f"https://some-random-api.ml/meme").json()
  image_url = r["image"]
  em = discord.Embed(title="**Meme**", color=16202876)
  em.set_image(url=image_url)
  em.set_footer(icon_url = ctx.author.avatar_url, text=f"Requested by {ctx.author.name}")
  await ctx.send(embed=em)

something like this would also generate a meme aswell

valid perch
heavy radish
valid perch
slate swan
valid perch
slate swan
spark estuary
slate swan
valid perch
slate swan
valid perch
#

And I cant read the dudes mind, so up to him to provide details like that imo. But likely

spark estuary
#

much easier

slate swan
#

ok

#

do you understand anything in the code I sent though?

#

@spark estuary

spark estuary
#

yes abit

slate swan
#

ok what is the r doing?

spark estuary
#

it takes meme from an api when the command is sent and then embeds it

spark estuary
slate swan
#

you can't just copy and paste

#

when you are learning it's key to understand what you are copy and pasting

spark estuary
#

yes you are right

slate swan
#

if you don't know what something does or means. Simply ask and someone will tell you

#

I am not the best coder but I know some

#

I try to help as much as I can but I don't know it all

spark estuary
slate swan
#

does anybody know what does this command mean i cant find the definition of what its use for?ive seen (self)but i dont know if its the same the command is:

is_self
valid perch
#

Kinda hard without code

slate swan
#

yeah

valid perch
#

command/functions can mean anything

slate swan
# slate swan can I see the code
async for submission in top:
        if not submission.is_self:
            all_subs.append(submission)
    random_sub = random.choice(all_subs)

    name = random_sub.title
    url = random_sub.url
    
    em = discord.Embed(title = name)

    em.set_image(url = url)
    await ctx.send(embed = em)
valid perch
#

What is submission

pliant compass
#

Anyone got some cool Discord bot ideas?

slate swan
slate swan
valid perch
#

My assumption is that is_self refers to if the poster of submission was the person fetching submissions

slate swan
# valid perch What is `submission`

its a bot that takes reddit memes and puts them in the chat and im trying to make it so it can only send memes with images in it and someone suggested to use that so it wont send the ones with only text in it and it will ignore it and find one with a image but i dont know what it means

spark estuary
slate swan
valid perch
slate swan
spark estuary
slate swan
pliant compass
slate swan
valid perch
pliant compass
spark estuary
slate swan
valid perch
#

You don't process commands. Read the pinned messages on it

boreal ravine
#

If I have an global error handler for MissingRequiredArgument and another one that justs sends the error how do I make it only send 1 error and not the other one?

foggy merlin
# boreal ravine If I have an global error handler for `MissingRequiredArgument` and another one ...

you can define a method called cog_command_error in your cog and put errors that are specific to your cog there. Then, in your global event handler, you want to create a check to see if a cog has a local error handler. If it does, return. If it doesn't go through with the global error handler. Heres an example you can see on how its implemented https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612

Gist

Simple Error Handling for ext.commands - discord.py - error_handler.py

boreal ravine
#

thanks

foggy merlin
#

np

heavy radish
#

Hello!! How do I read embeds sent by other BOTs?

foggy merlin
heavy radish
#

Oh, thanks...

valid perch
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

fleet axle
#

I have imported discord_buttons
and after running the code
it is saying no module "requests" found

#

How can i fix this?

spark estuary
valid perch
#

I see nothing to help with

spark estuary
fleet axle
valid perch
heavy radish
spark estuary
# valid perch Code?
client = commands.Bot(command_prefix='$')




@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

r = requests.get(f"https://some-random-api.ml/meme").json()
image_url = r["image"]
@client.command()
async def meme(ctx):
  r = requests.get(f"https://some-random-api.ml/meme").json()
  image_url = r["image"]
  em = discord.Embed(title="**Meme**", color=16202876)
  em.set_image(url=image_url)
  em.set_footer(icon_url = ctx.author.avatar_url, text=f"Requested by {ctx.author.name}")
  await ctx.send(embed=em)

  
def get_quote():
  response = requests.get('https://zenquotes.io/api/random')
  json_data= json.loads(response.text)
  quote=json_data[0]['q'] + " -" + json_data[0]['a']
  return (quote)
spark estuary
heavy radish
#

ok

heavy radish
spark estuary
#

nope

#

just no output

heavy radish
#

Thats weird

spark estuary
#

yes

heavy radish
#

has it worked before

spark estuary
#

yeah i mean the command worked separately before but when i copied it to my main bot it doesnt give output

heavy radish
#

Have u got any swiggles

#

Cause I'm as lost as you

spark estuary
heavy radish
#

Like the red line. swiggly ones

spark estuary
heavy radish
#

Oh, IDK man. I'm sorry

spark estuary
#

np

valid perch
heavy radish
#

I'll DM

spark estuary
valid perch
valid perch
spark estuary
#

yes

heavy radish
spark estuary
heavy radish
#

I'm trying to make a BOT

spark estuary
#

yes...

valid perch
spark estuary
# valid perch Show it
@client.event
async def on_ready():
  print('we have logged in as {0.user}'.format(client))

r = requests.get(f"https://some-random-api.ml/meme").json()
image_url = r["image"]
@client.command()
async def meme(ctx):
  r = requests.get(f"https://some-random-api.ml/meme").json()
  image_url = r["image"]
  em = discord.Embed(title="**Meme**", color=16202876)
  em.set_image(url=image_url)
  em.set_footer(icon_url = ctx.author.avatar_url, text=f"Requested by {ctx.author.name}")
  await ctx.send(embed=em)

  
def get_quote():
  response = requests.get('https://zenquotes.io/api/random')
  json_data= json.loads(response.text)
  quote=json_data[0]['q'] + " -" + json_data[0]['a']
  return (quote)


@client.event
async def on_message(message):
 if message.author==client.user:
   return

 if message.content.startswith('$hello'):
   await message.channel.send('Hello!')
 
 if message.content.startswith('$motivate me'):
   quote=get_quote()
   await message.channel.send(quote)

 if message.content.startswith('$fact'):
   fact=randfacts.get_fact()
   await message.channel.send(fact)
 
 if message.content.startswith('$jokes'):
   jokes=pyjokes.get_joke(language='en',category='all')
   await message.channel.send(jokes)
 
 new_message = datetime.now()
 currentTime = new_message.strftime("%H:%M:%S")
 if message.content.startswith('$time'):
   await message.channel.send(f"Time{currentTime}")
heavy radish
#

IDK how to explain in words

#

Can u join my server and I will represent?

spark estuary
#

sure

valid perch
#

So its the same issue I already gave you the answer to. Read this @spark estuary

reef shell
#

Bruh

boreal ravine
#

hm

heavy radish
#

Cereal Killer, I sent you the Link

spark estuary
boreal ravine
valid perch
boreal ravine
#

@spark estuary ```py
await bot.process_commands(message)

heavy radish
boreal ravine
#

with

heavy radish
#

I'm trying to make a BOT help advance the gameplay of another bot. The official bot is EPICRPG, In that bot, there is a Enchant option, the enchant always changes. So when we spam, we may accidently lose a good enchant. So what my BOT does is, before they spam in EPICRPG, they do a command on my bot like !enchant Omega, now when the EPICRPG gets an omega enchant, my BOT mutes the player for like 5 seconds

#

So i need my BOT to read EPICRPG's enchants and decide if it would mute or not

#

That's the best i can do with writting. I can give a representation if you would like

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

#

The project is open source and no payment is due for the help

boreal ravine
heavy radish
boreal ravine
#

what bot exactly did that

heavy radish
#

Its a private BOT. Alot of people make the same bot as its for the same EPICRPG Bot

boreal ravine
heavy radish
#

oH

boreal ravine
#

maybe some1 else knows how

river walrus
#

@heavy radishCheck message.embeds on on_message

heavy radish
#

hm

river walrus
#

And check if the author has the same id as the EPIC RPG

heavy radish
#

OOo

heavy radish
river walrus
heavy radish
#

i can explain u

deep bramble
#

hey i need a help i am currently making a discord bot

river walrus
#

Which lib

deep bramble
boreal ravine
deep bramble
river walrus
deep bramble
slate swan
#

and it's client.user

keen comet
# deep bramble

also the "messmessage.author" and "meessage.content.startswith" and also " message.channel.sen"

deep bramble
#

okay

slate swan
#

Yeah ^

deep bramble
#

any help editing this

#


class MyClient(discord.Client):

    async def on_ready(self):
        print('Logged on as', self.user)
        .format(client))

@client.event
async def on_message(message):
  if messmessage.author == client.user:
    return

if meessage.content.startswith('$Hello'):
   await message.channel.sen('Hello!')

   f'{client.user.tag}' ```
keen comet
#

and indent

river walrus
deep bramble
keen comet
hasty saddle
#

Anyone ones why it doesnt print at the bottom tho the channeltype is text?

@client.command()
async def gametester(ctx):
    print(ctx.message.channel.type)
    if ctx.message.channel.type == "text":
        print("Channetype is text")

That is the start of a command

manic wing
#

discord.Channel.type

#

it doesnt return str

#

do str(ctx.channel.type)

#

in the future you can print(type(object)) to see if its an str or not

#

in this case its discord.enums._EnumValue_ChannelType

shrewd barn
#

How to get id of sender?

spring flax
shrewd barn
spring flax
#

yes

shrewd barn
#

Worked, TY

spring flax
unkempt canyonBOT
#

id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.id "discord.User.id")
spring flax
#

yeah so once you have a member object you can use the attribute id

shrewd barn
#

It tags me, how can I make this without tag?

slate swan
#

mention_author = False

hasty saddle
#

In this line right here I am making an embed field for each answer in a table:

embed.add_field(name=question, value=answers[i], inline=True)

How to I print the 3rd answer?

shrewd barn
spring flax
floral jacinth
#

how remove all reaction of a message?

spring flax
unkempt canyonBOT
#

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

Removes all the reactions from the message.

You need the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
slate nymph
#

@bot.command(name='spam', help='Spams the input message for x number of times') @commands.is_owner() async def spam(ctx, amount:int, *, message): for i in range(amount): await ctx.send(message) if message.content.startswith("$stop"): break

#

how do i stop the above command if the user writes $stop

#

?

brisk helm
manic wing
slate nymph
#

ehh

#

any other way without importing task extension?

hasty saddle
#

Instead of "No" I want to see if the answer is like any word in a table. How do I do that?

elif answers[2] == "No":
manic wing
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None)```
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/stable/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
slate nymph
#

from discord.ext import tasks?

manic wing
#

yes

slate nymph
#

okau

manic wing
#

thats not external though

slate nymph
#

ok

#

i ll brb after testing

#

i m not sure what to do and how loops workk

#

but i m sure there must be some other way to stop the spam

hasty saddle
#

i only want the message to be started if it is from the right person and from the right channel. How can I do that?

try: message = await client.wait_for("message", timeout=200.0)
except asyncio.TimeoutError:
embed = discord.Embed(title="You were too slow! Apply again.")
await DM.send(embed=embed)
stiff ermine
#

does on_member_join()
works even if some member leave the server and rejoin ?

stiff ermine
#

...

#

for some reason it didnt les see

#

this should do the thing right?

spring flax
#

Interesting

stiff ermine
#

yea

#

i dont see them as bots...

#

😄

spring flax
#

yes what you did above should work as long as you have member intents on.

stiff ermine
#

and i think i fixed it

#

yes intents was the thing

past ermine
#

is there an event that's the opposite of ```py
on_ready

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

slate swan
past ermine
#

like when the bot goes offline

brittle ingot
#

On_disconnect

paper fern
#

no docs

slate swan
#

yeah

lone aurora
#
@client.event
async def on_message(message):
    if message.channel.name == "cmdtest":
        channel = client.get_channel(888708490133123072)
        embed = discord.Embed(
        title = '',
        description = '',
        colour = 0
        )
        embed.set_footer(text='By oSeatch#6969')
        embed.set_author(name=message.author)
        embed.add_field(name='Test', value=message , inline=False)
        await channel.send(embed=embed)
        await message.delete()``` am i going wrong somewhere?
brittle ingot
#

!d discord.on_disconnect

unkempt canyonBOT
#

discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_connect "discord.on_connect") call.
lone aurora
#

no error its just that

slate swan
#

await client.process_commands(message) btw use this

slate swan
lone aurora
#

it works upto this,

message gets deletes : ✅
embedded message is sent : ✅

#

but here's what the embedded message sends

slate swan
#

value = message.content

#

not message

slate swan
#

message represents a discord Message

lone aurora
#

oh

slate swan
#

!d discord.on_disconnect

unkempt canyonBOT
#

discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.

This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_connect "discord.on_connect") call.
slate swan
#

oh nvm

hasty iron
#

and it can be called multiple times

brittle ingot
#

^^

lone aurora
#

wowo thanks a lot mate

lucid ravine
#

anyone willing to help me with this issue which is that im trying to upload my bot to a hosting service but i keep getting this error.

past ermine
brittle ingot
#

Try to run: python3 —version

slate swan
#

epic spam 20 hours later

past ermine
#

d! discord.on_ready

slate swan
past ermine
#

!d discord.on_ready

unkempt canyonBOT
#

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

Warning

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

You'll have to try making a requirements.txt and setting the imports in settings to this file

hasty iron
#

thats not required

past ermine
#

help pls?

hasty iron
#

it just makes installing dependencies easier

#

but some services like heroku do require them

lucid ravine
#

im so confused im very new so if you could boil it down for me

lone aurora
#

any clue how next to Seatch#9766 i can make my pfp appear? it should vary by author

brittle ingot
past ermine
#
@client.event
async def on_disconnect():
  print("GelbieLevel goes offline.") 
  channel = client.get_channel(881463922807431173)
  await channel.send("GelbieLevel is offline.")
``` my code
hasty iron
#

how are you closing the bot

past ermine
#

stop button

hasty iron
past ermine
#

yes

lucid ravine
opal pewter
#

Generally if the bot closes, it can't send a message in any channel

opal pewter
fleet axle
#

hey, can anyone help me
I have created a discord.py Button calculator
but when I click on any button it says
"This Interaction Failed"

#

Anyone can help me?

surreal creek
#

how to get bot avatar ?

#

anyone there to help ?

lone aurora
#
embed.set_author(name=message.author, icon_url=?)``` what would i add after at `?` to make it so that it shows the author's pfp
lone aurora
#

ah ok thanks

surreal creek
#

?

lone aurora
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\HP\Desktop\cmdtests\main.py", line 42, in on_message
    await channel.send(embed=embed)
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required``` my code is working but im getting this error
slate swan
lone aurora
#

i mean its not an error, the code works and the message goes through

unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

lone aurora
#

is there any way for me to fix this?

slate swan
#

!d discord.ClientUser.edit

unkempt canyonBOT
#

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

Edits the current profile of the client.

If a bot account is used then a password field is optional, otherwise it is required.

Warning

The user account-only fields are deprecated...
slate swan
#

finally

slate swan
lone aurora
#
@client.event
async def on_message(message):
    if message.channel.name == "cmdtest":
        channel = client.get_channel(888708490133123072)
        embed = discord.Embed(
        title = '',
        description = '',
        colour = 0
        )
        embed.set_footer(text='By oSeatch#6969')
        embed.set_author(name=message.author, icon_url=message.author.avatar_url)
        embed.add_field(name='Test', value=message.content, inline=False)
        await channel.send(embed=embed)
        await message.delete()```
#

as u can see, it does work but also shows the error

surreal creek
lone aurora
#

@surreal creek send me the pfp of the bot in DMs

surreal creek
#

uh

#

i don't have the pfp :/

#

is there any other way in the code

slate swan
#

bot.user.avatar_url

surreal creek
#

like bot.avatar smthng like that

lone aurora
#

client.avatar_url

surreal creek
lone aurora
slate swan
#

or client depends on what you define it

lone aurora
#

yea i use client

#

bro i thought alot of people were typing until i realised it was u..

lone aurora
slate swan
#

remove the title and description

lone aurora
#

ok ill try that

#

nope i tried, still same error

#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\HP\Desktop\cmdtests\main.py", line 40, in on_message
    await channel.send(embed=embed)
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required``` same thing
slate swan
#

the message.content is none

#

so it's empty

fleet axle
#

anyoen here to help?

lone aurora
slate swan
slate swan
lone aurora
#

i mean this error doesn't hurt me, its just annoying

slate swan
#

instead of checking on_message

lone aurora
fleet axle
slate swan
lone aurora
#

rather than having someone do a command i want it to directly make it an embed, ignoring if its a command or not

slate swan
drifting arrow
slate swan
#

yep

drifting arrow
#
if not message.content:
    field_value = ...
#

which is better imo

slate swan
#

yeah , its more efficient

hoary yacht
#

c++ discord bot coding be like

boreal ravine
paper fern
#

does anyone know a good tutorial for making your bot send embeds?

#

or could explain/help me

boreal ravine
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

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

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/stable/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.
hoary yacht
#

thoughts on discord js

boreal ravine
#

arguments?

boreal ravine
#

then go learn python first?

scarlet snow
#

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

paper fern
#

thanks

#

lucas

scarlet snow
#

well he can make the bot without knowing py tho but he would struggle a lot

boreal ravine
#

yes

paper fern
#

yeah I already am

#

I have made it send messages and reply to set messages but thats about it

boreal ravine
#

lots of people struggle to fix syntax errors and indentation errors and thats about it lmfao

paper fern
#

I can fix those

#

because my knowledge isnt that basic but I just don't know how to write it all out sometimes

dawn lion
#

Where can I get docks about all the events?

paper fern
#

documents?

#

or docks

dawn lion
#

docs

paper fern
dawn lion
#

yes

#

of event

dawn lion
#

fanke

#

Fuck

#

You

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

paper fern
lament mesa
river walrus
#

We're in the early phases

#

And tbh I'm waiting on Py 3.10 to start the project since match-case makes things way eaiser

slate swan
#

Heyhey! So Im trying to make a discord bot and normally it works all fine, but this time it said, no module named discord was found

So I looked into .local/lib/python3.8/site_packages and there is the discord folder

Anyone knows what Im doing wrong?

valid perch
#

typed / tested / focus on scaleability?

river walrus
slate swan
#

Its 3.8

river walrus
#

Maybe 3.7

slate swan
#

Hm I see

#

Any way I can uh... fix that???

#

I just did pip install discord

river walrus
#

Oh

#

Test pip --version

slate swan
#

ok

river walrus
#

And post the output

slate swan
#

Wait its a bit complicated cuz Im using pterodactyl

river walrus
#

🤷‍♂️ I haven't worked with that

river walrus
#

discord installs the old one I believe

slate swan
#

Ok

#

WAIT

#

Its 3.9.7, wth?

#

So pterodactyl creates a folder for 3.8 but the version is 3.9

#

Thats not supposed to happen ;-;

river walrus
#

Your pip is configured for 3.8

#

But your project is 3.9.7

#

That's correct?

slate swan
#

Im a bit confused

river walrus
#

Your pip command installs for 3.8

#

Your project is in 3.9.7

#

You gotta match the two

slate swan
#

Yea I wonder why

river walrus
#

Tbh Idk

slate swan
#

Like Im using 2 different hosts, now I used another one than normally. I mean its both pterodactyl so idk?

brazen seal
#

how i can get all players and online players on the server?

brazen seal
#

my xD

slate swan
#

oh i see

brazen seal
#

i want Bot has in status OnlinePlayers/AllPlayers

#

you know what i mean?

slate swan
#

wait. do you mean your discord server or like a minecraft server etc.

brazen seal
#

discord server

#

if it was minecraft server i don't asking here

slate swan
#

idk how i would do it in a status but i could picture how i would do it in a command

valid perch
#

!d discord.User

slate swan
#

so i have this code. the first part which send the support text works just fine. the second part doesnt tho and it doesnt give ant errors

#
@commands.Cog.listener()
    async def on_voice_state_update(self, ctx, before, after):
      logschannel = ctx.guild.get_channel(886331433134727178)
      logschannel1 = ctx.guild.get_channel(886331475681742888)
      if before.channel is None and after.channel is not None:
        if after.channel.id == 886331304944214077:
          await logschannel.send(f"Ο  μπήκε στο Support!")
      elif before.channel is None and after.channel is not None:
        if before.channel is None and after.channel is not None:
          if after.channel1.id == 886331342030245928:
            await logschannel1.send(f"Ο  μπήκε στο Donate!")
valid perch
#

wdym first / second

slate swan
#

first

#

      if before.channel is None and after.channel is not None:
        if after.channel.id == 886331304944214077:
          await logschannel.send(f"Ο  μπήκε στο Support!")
#

second

#
elif before.channel is None and after.channel is not None:
        if before.channel is None and after.channel is not None:
          if after.channel1.id == 886331342030245928:
valid perch
#

The initial if will always run because they have the same conditions?

slate swan
#

dont get you

valid perch
#

When your 'first' runs, its never going to go to the elif

#

Thats just how if / elif works

#

Then since they both have the same condition. Your elif will never run, because if its true then the if runs

slate swan
#

oh i see

valid perch
#

Get rid of the elif and put them under the first if

#
if cond:
  if channel == 1:
  elif channel == 2:
slate swan
#

like this?

#
logschannel = ctx.guild.get_channel(886331433134727178)
      logschannel1 = ctx.guild.get_channel(886331475681742888)
      if before.channel is None and after.channel is not None:
        if after.channel.id == 886331304944214077:
          await logschannel.send(f"Ο  μπήκε στο Support!")
            if before.channel is None and after.channel is not None:
              if before.channel is None and after.channel is not None:
                if after.channel1.id == 886331342030245928:
                  await logschannel1.send(f"Ο  μπήκε στο Donate!")
valid perch
#

Also you have the same condition, its kinda funny. You have an if for a condition, then if thats true you go to another if, which is the same condition haha

#

Shit no

#
if before.channel is None and after.channel is not None:
  if after.channel.id == 886331304944214077:
      await logschannel.send(f"Ο  μπήκε στο Support!")
  elif after.channel1.id == 886331342030245928:
    await logschannel1.send(f"Ο  μπήκε στο Donate!")
#

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

valid perch
#

Also, would recommend looking into a bit more python. Discord.py is not beginner friendly

slate swan
#

ok i will

#

the code still doesnt work

valid perch
#

print the values, see what they are

slate swan
#

and it doesnt give any errors

#

excuse me, how do i get input from a user in private messages?

#

like if i have a command : !verify that they have to send me in dms

#

how do i get the input?

harsh cradle
#

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

#

pls fix

harsh cradle
# valid perch code.
@bot.command(pass_context=True)
async def help(self, ctx):
        embed = discord.Embed(title="Help!", description="How to use the commands!", timestamp=datetime.datetime.utcnow(), colour=discord.Colour.blue())
        embed.add_field(name=f"{bot.PREFIX}ping", value="This command is too show the latency of the bot", inline=True)
        embed.add_field(name=f"{bot.PREFIX}purge", value=f"Syntax: {bot.PREFIX}purge (amount of messages), This command is too delete certant amount of messages in a channel!", inline=True)
        embed.add_field(name=f"{bot.PREFIX}tempmute", value=f"Syntax: {bot.PREFIX}tempmute (member) (time) (time delay(example: s, m, h, d)) (reason), This command is to temperaly mute a member!", inline=True)
        embed.add_field(name=f"{bot.PREFIX}mute", value=f"Syntax: {bot.PREFIX}mute (member) (reason), This command is to permentaly mute a member untill unmuted with a command", inline=True)
        embed.add_field(name=f"{bot.PREFIX}unmute", value=f"Syntax: {bot.PREFIX}unmute (member), This command is to unmute a member forcefully", inline=True)
        embed.add_field(name=f"{bot.PREFIX}kick", value=f"Syntax: {bot.PREFIX}kick (member) (reason, This command is to kick a member from you're guild! They still can rejoin if given an invite)", inline=True)
        embed.add_field(name=f"{bot.PREFIX}tempban", value=f"Syntax: {bot.PREFIX}tempban (member) (time) (time delay(example: s, m, h, d)) (reason), This command is to temperaly ban a member untill time is up or unban command is called on the member", inline=True)
        embed.add_field(name=f"{bot.PREFIX}ban", value=f"Syntax: {bot.PREFIX}ban (member) (reason), This command is to permentaly mute a member untill unbannedd with a command", inline=True)
        embed.add_field(name=f"{bot.PREFIX}unban", value=f"Syntax: {bot.PREFIX}unban (member), This command is to unban a member forcefully", inline=True)
        await ctx.send(embed=embed)
slate swan
#

remove self parameter

harsh cradle
valid perch
valid perch
#

Also pass_context is no longer needed

slate swan
harsh cradle
#

i begginer

#

oh you mean

#

self, ctx?

valid perch
hasty iron
#

also subclass commands.HelpCommand for help commands

hasty iron
#

what

slate swan
hasty iron
#

you can make it a thing yourself

#
bot = commands.Bot(*args, **kwargs)
bot.PREFIX = 'h'
slate swan
#

im aware , but are they doing it?

hasty iron
#

who knows

boreal ravine
hasty iron
#

no, it will raise an AttributeError

slate swan
#

no , it will be an error

#

yep

boreal ravine
#

Will it?

boreal ravine
#

NameError: name 'ducky' is not defined

hasty iron
#

what

#

!e ```py
class Obj:
pass

obj = Obj()
print(obj.a)

unkempt canyonBOT
#

@hasty iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 | AttributeError: 'Obj' object has no attribute 'a'
slate swan
boreal ravine
#

oh because he used client/bot

#

makes sense I didn't see that though

crimson tendon
#

How can I make these tasks, start at different time ?
the 1st when I start the bot, and the 2nd after 15min, and 3rd after 30min, and 4th after 45min```py
update_tweets.start()
FuturaSciences.start()
CNRS.start()
BRGM.start()

lament mesa
manic wing
#

and do the next on

slate swan
crimson tendon
#

okay thanks !!

hasty iron
#

dont do it inside the on_ready

crimson tendon
lone aurora
#

is there a message_delete event?

hasty iron
#

async def start_tasks():
  await bot.wait_until_ready()
  first_task.start()
  await asyncio.sleep(time)

  # and start all the other tasks

bot.loop.create_task(start_tasks())
bot.run(*args, **kwargs)
``` here is an example
hasty iron
unkempt canyonBOT
#

discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.

If this occurs increase the `Client.max_messages` attribute or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.

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

aight thanks

lone aurora
#
@client.event
async def on_raw_message_delete(message):
    channel1 = client.get_channel(883251215637561399)
    await channel1.send(f"{message} was deleted")``` should this work?
#

well it didnt work

#

crappp

#

its doing this

valid perch
#

!d discord.Message

unkempt canyonBOT
#

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

`x == y` Checks if two messages are equal.

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

`hash(x)` Returns the message’s hash.
valid perch
#

Your sending the object

hasty iron
#

!d discord.RawMessageDeleteEvent

unkempt canyonBOT
#

class discord.RawMessageDeleteEvent```
Represents the event payload for a [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event.
hasty iron
#

thats what you're sending

lone aurora
#

i still have 0 clue how to do this

hasty iron
#

why are you sending the class

lone aurora
#
@client.event
async def on_raw_message_delete(payload):
    channel1 = client.get_channel(883251215637561399)
    await channel1.send(f"{discord.Message} was deleted")```
lone aurora
hasty iron
#

why discord.Message

hasty iron
hexed turtle
#

payload has a message_id attribute

hasty iron
#

and a cached_message attribute that can return a Message object

lone aurora
#

i- i dont get someone end me

hasty iron
#

wat

lone aurora
#

nvm it works now

#
@client.event
async def on_message_delete(message):
    channel_id = client.get_channel(883251215637561399)
    await channel_id.send(f"{message.content} : This message was deleted" )``` im ok with the chibi code ._.
boreal ravine
#

Developer Mode > Profile > Right Click

hasty iron
#

you can use discord.utils.get(Guild.roles, name=the_name)