#discord-bots
1 messages · Page 478 of 1
You can use Guild.ban and snowflakes
await guild.ban(discord.Object(id))
why it says this when i am trying to join a voice channel
!PyPi pynacl
^ you need to install this first
got it thanks
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 ! ')
it's author instead of authour
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
what you're making here is a class variable, not a global variable
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
the guild ID is probably wrong?
ill host for u but u probably dont trust me
buy an old computer and shove an SSD into it and install linux on it
why an ssd
old computers run like shit
unless you're trying to store a lot of things go for an ssd
i have 400gb storage and 16gb of ram on my vps
its pretty quick
i host like some random 30 something things on it
not overspending on vps?
i used digitalocean but didn't feel like paying further lol since i was living off github education anyways
actualy its 14 a month
nope, they're all right. i confirmed
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
@commands.is_owner()
thats what im trying to do but how do i check if its in the list?
print statements are always safe ways to check if things are working properly
ill just have a list of owner ids at the top of the file like py OWNER-IDs = ["1231231231", "23123123123"]
the uppercase is pissing me off
lol
for x in owner_ids:
print(x)
you cannot use - in variables
i wont that was just a example
alright then
what would that do?
so can anyone help
the guild was not found in the bot's cache
print all values in the list
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)
if ctx.author.id in owner_ids:
# do something
you want to make sure that the command is being used by the bot owner only?
i just dont know how to check the list for the authors id
if id:
send message
thanks
lmfao.
so how do I fix that
yes but without using the is owner thing because i need more then 1 person and not a team
is the bot in the guild you are trying to get?
yes
!d discord.ext.commands.is_owner use this
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").
i cant
i am not owner of the bot
has all permissions too
did u even read my message
and in your commands.Bot part , declare owner_ids = []
i didnt know u can do that
add your id in the list
ok
@slate swan do you know anything else that may be the issue
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
try not using the class to get the guild , use it withing the command function
that defeats the purpose of what I am trying to do
make a function instead of the class which returns your role?
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
functions can be imported as well
I'm aware but how would a function work when I'm only trying to store variables
you are trying to fetch only the role from the class right?
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)
def function_for_role():
role = #get the role
return role```
it returns the role whenever you call the func
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
why do you actually want to use it in a class / func tho?
just for importing?
owner ids must be in int type
remove those quotes
oh
that fixed it
u can also do if ctx.author.id in bot.owner_ids OR if ctx.author.id == bot.owner_id
Is there a way to tell if a user Is online
!d discord.Member.status
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.
help
guild_id is None. Could be the wrong ID
Also please don't make them class vars
Is there any module called discord_components?
no
tell me how to do it then pls
Yes
why is it showing this error?? i have installed it
wait lemme restart
Make them instance variables... Define them in the init
self.guild_id =
Install from Package Manager
# 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?
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
yeah i am doing now
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)
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
im gonna make a config.json instead
Your wish
how do I add a role to a user without the use of a command
Get the member object with get_member in the event and just add roles to it?
is message.author okay?
Sure
what is the function for adding roles and how do i use it?
!d discord.Member.add_roles
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.
how can i get a discord.Role object from a role ID
is there a way to make a command which googles the term and returns the first link?
is discord_components enough for making buttons or any other module is needed?
It's enough
ok
i am confused
#bot-commands
ohh sorry
Bro...
just testing what it really does
Ah ok
!e
for i in range(2):
print('Hello, World!')
@ocean leaf :white_check_mark: Your eval job has completed with return code 0.
001 | Hello, World!
002 | Hello, World!
ok
i wonder how this bot was made
it is also a python interpetor
and also controls this entire server
@ocean leaf bro #bot-commands
!source
hey guys, is there any way to specify the cog i wanna get the list of the bots commands from?
i forgor 💀
?
Bot.get_cog().get_commands()
U will have to use the google API
i tried for command in get_cog("cogname").bot.commands() lol
Bro
wat
get_cog().get_commands()
....?
this will return a list of the commands, so why shouldnt i iterate through all of them immediately
Bro, your message doesn't make sense...
then what does that return
can you recommend a video i can watch about the api? not necessarily about d.py bots, just about how the api can be used in python
Sorry, idk
alright np
ohh
ok sorry
Hey, Can anyone help how can I add server acknowledgement in userinfo command
wym?
i'll check it out, thanks
how do i give a bot permission to dd roles to users
What's the exact purpose of Discord.HTTPErequest?
@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?
HTTPEexception*
Enable manage roles
In settings
it can happen when the bot doesn't have the perms to send DMs to a user and stuff
you gotta check the perms
Thx, luv u
(:
Thanks
So, uh
help error
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)```
I mean
i want it like it finds the first search or sum like groovy and rythm kind
like keep ` this symbol
Lemme check
help me pls on this one i am stuckkkk
for black square
!ytdl
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 Could you show us your code, I can guess what you've done but seeing the code would help
would it not get taken down?
just a sec
I'd imagine you're using discord.Client rather than discord.ext.commands.Bot
umm yes
Then yes, that's the issue
how do i give a bot user permission to give roles to other users
no , its commands.Bot
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='...')
yeah small mistake
so this shoud fix it right?
yep
It'll fix the issue you're currently facing, though there may be more
So start with that, see what happens next
it fixed the error but i want tthe bot to send memes from reddit which isnt happening
requests is blocking , the urllib library blocks asynchronous code
You may use aiohttp , or reddit's api
!d str.split
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:
so blurry
?
ty
Why. Did. You. Delete. The. Message.
my bot command is not working can someone help me pls
Code? Error?
no error it just doesnt do anything lemme share tge code
ok.
Try making an error handler so we know whats the error lol
wdym?
i mean i had errors before but solved it
now it doesnt work
hm
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
@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)```
can I see the error?
there aint any error...when i am sennding the command !meme....it doesnt respond
if it's not working there should be an error. are you sure the bot is online whilst doing !meme ?
yes
no wait
my bad
i didnt check cmd i got an error
what was the error?
sorry
the error
copy and paste it here
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 . . .
it's an error..
yes....my bad.....how do i fix it tho
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)
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
!code
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.
i pasted it
await r.json(content_type=None)
try that
in the last line of my code right
???
no where it says memes=
can you show us the code?
!paste
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.
ohk
Hello. Where can I learn Python for discord BOTs?? I just completed the W3 Schools Python workshop
https://vcokltfre.dev/ this one is good, a pydis staff member made it
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Hm
What
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)
??
new eeror @slate swan
why is the error a decode error lol
await r.json(content_type='text/html')
try this
this should be memes=content_type='text/html'
right?
memes=await r.json(content_type='text/html')
what line
same error again
18
How can i add buttons in a discord.py bot?
still need help?
use a dpy 2.0 or another lib/fork thats 2.0
I think I figured it out, lemme see
if not lmk
i need pls....i beg help me to figure it out
What does import discord mean
Importing a module?
will import the discord module
Whoah what r those import words
No shitpost please
just imprting modules.
It totally flew over my head
Nicee
that I didn't add the listener
Where do I get those import words
👍
How do u guys know what to type after the word import
and not it accuses me of not having a listener???
Modules
You import libraries
now*
go figure
Yes
its on_command_error not OnCommandError
Pretty sure that there's no difference and it's just a class name
it matters
It does?
I could copy free modules from Google?
yep
yeah it does matter
Well, today I learnt that class names make a difference
not literally copy. just use the module
import aiohttp
etc..
can you figure it out? my error
post it again
the code or the error?
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.
I was trying to execute the cog, wtf
what happend lol
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)
I stared the screen for a solid minute
Trying to run the cog
Until I realized that I wasn't on my main file
.
Have you put {} into the start of your JSON?
!json
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.
can pls see the code and tell which line you talking about
Read this
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
could you elaborate or show me a place where i can read about this
whats the code?
@commands.Cog.listener()
@commands.Cog.listener()```
cog is capitalized so it's Cog, cog is a module and Cog is a class
.
U dont need the parentheses
you do.
oops, thanks
you do?
and I tried to run the cog again
Master Branch For Dpy = https://discordpy.readthedocs.io/en/master
A Popular fork for 2.0 = https://pycord.readthedocs.io/en/master
and other forks/libs also
what does it mean??? can someone explain me?
it means you need
{
"this": "thingy lol"
}
can i ping the helpers?
Why?
becoz i need help
With what?
my code
Well, whats your code and whats the error
,
.
i havent created any json file
how is this done? Is there db involved?
Well, then theres you problem hahaha
can you pls help step by step?
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")
i was told to do it here
What have I done wrong?
Try remove it
error?
I told him to add a content type. my bad though
Assuming you have your bot.run line missing from the code block, nothing I can see
noe
error
Might not be that
Whiich is?
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')
yes...?
just use a api
How about now
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()
bot.run(getenv("TOKEN"))
this?
change that to the url??
*The url in the error
!code
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.
i dont know about the error url i am talking about the one in my code
Weiird
Anyone?
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
And whats the problem your having?
the BOT.run is something wrong
whats this?
Sorry, discord was just munting the url
code that will generate a meme and embed it
Care to defiine "something wrong"
I think that he isn't putting his bots token in "TOKEN"
no way to fix my code then?
there is a way just I don't know it and the code I sent will also do what you want
getenv should work in theory, assuming its set
probably isn't
And I cant read the dudes mind, so up to him to provide details like that imo. But likely
lmao yeah
thanks its working
much easier
yes abit
ok what is the r doing?
it takes meme from an api when the command is sent and then embeds it
ok welp
sorta
you can't just copy and paste
when you are learning it's key to understand what you are copy and pasting
yes you are right
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
thanks for your help and time
no problem, good luck
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
Kinda hard without code
yeah
command/functions can mean anything
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)
What is submission
Anyone got some cool Discord bot ideas?
its a reddit submission
Command to see current BTC and ETH prices.
My assumption is that is_self refers to if the poster of submission was the person fetching submissions
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
.
hey so i copied the command to my main bot code and now it doesnt work....no error whatsoever it just doesnt send the meme when requested
i dont get it
Add some print statements, is it being called? How far does it get
double check if there was a error.
no error i checked
if not then do this @spark estuary
Thanks.
I can help possibly too
If your looking at posts. is_self refers to if its your post or someone else's would be my guess. For the proper thing you should probably read the docs
Wouldn't I just need to make a http request to some API that gives me the data?
shall i add a return statement?
ok thanks and i did i just couldnt find it
a little headstart for btc..
https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR
simple api for it 😉
Thanks.
You don't process commands. Read the pinned messages on it
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?
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
Simple Error Handling for ext.commands - discord.py - error_handler.py
thanks
np
Hello!! How do I read embeds sent by other BOTs?
You would need to get the Message object, then access the .embeds attribute
Umm....Is there a tuorial
Oh, thanks...
!d discord
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.
I have imported discord_buttons
and after running the code
it is saying no module "requests" found
How can i fix this?
hey can you help me?
I see nothing to help with
pip install requests
my code it isnt giving me the output
ok thanks
Heyy, are you free?
Code?
Heyy, do you know discord.py?
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)
have u imported and stuff
yes
ok
You're not getting any error right?
Thats weird
yes
has it worked before
yeah i mean the command worked separately before but when i copied it to my main bot it doesnt give output
now whats that
@valid perch
Like the red line. swiggly ones
no the code has no errors/typo i guess its a logic error idk
Oh, IDK man. I'm sorry
np
Yes
I'll DM
Is that full code
no just a bit
Don't do unpaid dm support
Got on_message?
yes
Oh
what do you need help with?
I'm trying to make a BOT
yes...
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}")
sure
So its the same issue I already gave you the answer to. Read this @spark estuary
Bruh
hm
hmm got some idea but can you help me to fix it
y use .format and f strings just use one man 🤨
The message I linkedd is your issue, and it shows you how to fix it. Without spoonfeeding you theres not much more I can do
@spark estuary ```py
await bot.process_commands(message)
Heyy, you reckon u can help?
with
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
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
idk if you can read embeds tho
WDYM, The BOT i'm trying to make has been made before by others obv
what bot exactly did that
Its a private BOT. Alot of people make the same bot as its for the same EPICRPG Bot
Nice idea
yeah but i dont know how to "read embeds" lmfao
oH
maybe some1 else knows how
@heavy radishCheck message.embeds on on_message
hm
And check if the author has the same id as the EPIC RPG
OOo
Is anyone up to lend a hand?
u reckon u can help me?
I guess so
i can explain u
hey i need a help i am currently making a discord bot
What type of help
Which lib
indents
can you?
f'{client.user.tag}'
same the syntax error
also the "messmessage.author" and "meessage.content.startswith" and also " message.channel.sen"

okay
Yeah ^
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}' ```
spel it correctly
and indent
I suggest you learn Python first
okay

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
it isnt an str
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
How to get id of sender?
to get the ID of a user invoking the command
ctx.author.id```
I use message instead of ctx, Will it work if i use message.author.id? TY btw
yes
Worked, TY
id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User.id "discord.User.id")
yeah so once you have a member object you can use the attribute id
It tags me, how can I make this without tag?
mention_author = False
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?
await message.reply("y", mention_author=False)```
Did you mean this one? If no, Where do I use it?
yes
for the third item in a list, index to [2]
how remove all reaction of a message?
!d discord.Message.clear_reactions
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.
@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
?
You need to do next command
you cant break out of a for loop like that - use a tasks.loop to send the messages or make a dict with the author id and in the for loop check to see if a key is in a dict
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":
elaborate
tasks aren’t difficult and they arent external
!d discord.ext.tasks.loop
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").
from discord.ext import tasks?
yes
okau
thats not external though
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
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)
does on_member_join()
works even if some member leave the server and rejoin ?
yes
your bot instance is marie?
Interesting
yes what you did above should work as long as you have member intents on.
is there an event that's the opposite of ```py
on_ready
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
Wdym opposite of?
like when the bot goes offline
On_disconnect
no docs
yeah
@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?
!d discord.on_disconnect
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.
why is there an error?
no error its just that
await client.process_commands(message) btw use this
so is it not working or what?
it works upto this,
message gets deletes : ✅
embedded message is sent : ✅
but here's what the embedded message sends
It's called when the bot is unable to connect....
message represents a discord Message
oh
!d discord.on_disconnect
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.
oh nvm
and it can be called multiple times
^^
wowo thanks a lot mate
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.
doesnt work
Try to run: python3 —version
epic spam 20 hours later
d! discord.on_ready
I know that hosting service, used it before
!d discord.on_ready
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.
In that hosting's panel , add discord.py in addition py packages
You'll have to try making a requirements.txt and setting the imports in settings to this file
thats not required
help pls?
it just makes installing dependencies easier
but some services like heroku do require them
im so confused im very new so if you could boil it down for me
any clue how next to Seatch#9766 i can make my pfp appear? it should vary by author
Wdym it doesn’t work? Have you tried adding a print statement to see if it’s firing?
yes, added print and a message that sends
@client.event
async def on_disconnect():
print("GelbieLevel goes offline.")
channel = client.get_channel(881463922807431173)
await channel.send("GelbieLevel is offline.")
``` my code
how are you closing the bot
stop button
anyone? ._.
stop button?
Generally if the bot closes, it can't send a message in any channel
I doubt it works that way. It ends the execution of the whole program.
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?
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
?
message.author.avatar_url
ah ok thanks
?
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
Because the embed field is empty
i mean its not an error, the code works and the message goes through
No documentation found for the requested symbol.
is there any way for me to fix this?
!d discord.ClientUser.edit
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...
finally
send the code
@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
but i want bot's avatar
oh then u can just upload the link to the png
@surreal creek send me the pfp of the bot in DMs
bot.user.avatar_url
like bot.avatar smthng like that
client.avatar_url
k
idk if this will work im just guessing
or client depends on what you define it
yea i use client
bro i thought alot of people were typing until i realised it was u..
umm @slate swan sorry for the ping but any clue?
remove the title and description
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
yes
?
anyoen here to help?
but then how does it register my message if its empty
idk never used buttons
have you tried making commands instead
i mean this error doesn't hurt me, its just annoying
instead of checking on_message
i want it to be an event, ive already done this with commands
oh
you'll have to maybe try reading the docs it may be issues with code or timeout errors something like it
rather than having someone do a command i want it to directly make it an embed, ignoring if its a command or not
ok
you can assign a string if no message is sent using py if message.content == None: field_value= ....
You can also write this as if not message.content:
yep
yeah , its more efficient
dude clear ur pings
does anyone know a good tutorial for making your bot send embeds?
or could explain/help me
!d discord.Embed
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.
arguments?
good lib honestly it has like 90% coverage of the discord api
then go learn python first?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
well he can make the bot without knowing py tho but he would struggle a lot
yes
yeah I already am
I have made it send messages and reply to set messages but thats about it
lots of people struggle to fix syntax errors and indentation errors and thats about it lmfao
I can fix those
because my knowledge isnt that basic but I just don't know how to write it all out sometimes
Where can I get docks about all the events?
docs
discord.py docs?
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
?
Can you send the for the github repo
It's empty for now tho
I'm gathering recruits because I can't do it all alone (uni)
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
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?
typed / tested / focus on scaleability?
Are you sure your python isn't 3.9?
Can you send your pip install command that you use?
Oh
Test pip --version
ok
And post the output
Wait its a bit complicated cuz Im using pterodactyl
🤷♂️ I haven't worked with that
try pip install discord.py
discord installs the old one I believe
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 ;-;
Im a bit confused
Your pip command installs for 3.8
Your project is in 3.9.7
You gotta match the two
Yea I wonder why
Tbh Idk
Like Im using 2 different hosts, now I used another one than normally. I mean its both pterodactyl so idk?
how i can get all players and online players on the server?
what server?
my xD
oh i see
wait. do you mean your discord server or like a minecraft server etc.
idk how i would do it in a status but i could picture how i would do it in a command
okay
!d discord.User
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!")
wdym first / second
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:
The initial if will always run because they have the same conditions?
dont get you
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
oh i see
Get rid of the elif and put them under the first if
if cond:
if channel == 1:
elif channel == 2:
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!")
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
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Also, would recommend looking into a bit more python. Discord.py is not beginner friendly
print the values, see what they are
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?
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
pls fix
code.
this is your 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)
remove self parameter
where
Lol no, copied it and fixed the other guys. Why
got it
i dont know where parameter
i begginer
oh you mean
self, ctx?
Read your code. I think theres only self once, so uh. That be the one
sry and thanks
also subclass commands.HelpCommand for help commands
or dont
what
is commands.Bot.PREFIX a thing? (im unsure , it can be an issue as well)
you can make it a thing yourself
bot = commands.Bot(*args, **kwargs)
bot.PREFIX = 'h'
im aware , but are they doing it?
who knows
if they didnt do it then the embed will just be bot.Pefix Command Name
no, it will raise an AttributeError
Will it?
true but its a name error
NameError: name 'ducky' is not defined
@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'
yes.
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()
subclassing commands.HelpCommand will make stuff a bit more easier
do it in on_ready then asyncio.sleep for 15 min
and do the next on
in your on_ready event , you would like using asyncio.sleep
okay thanks !!
no
dont do it inside the on_ready
so how now ?
is there a message_delete event?
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
!d discord.on_message_delete
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.
aight thanks
thanks !!
@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
!d discord.Message
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.
Your sending the object
!d discord.RawMessageDeleteEvent
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.
thats what you're sending
why are you sending the class
@client.event
async def on_raw_message_delete(payload):
channel1 = client.get_channel(883251215637561399)
await channel1.send(f"{discord.Message} was deleted")```
brain = small
why discord.Message
look at the attributes of this
payload has a message_id attribute
and a cached_message attribute that can return a Message object
i- i dont get someone end me
wat
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 ._.
Developer Mode > Profile > Right Click
you can use discord.utils.get(Guild.roles, name=the_name)
