#discord-bots
1 messages Β· Page 598 of 1
@slate swan can we use embeds in loop
sure why not
then make your bot check the data and unmute the muted users accordingly
yes
hmm oki ty , oki ty homo
π³
I don't know how to make seconds, days, weeks, months in a function and check them so that they can be used in a command.
For example: !mute <@member> 6s Violates the rules.
@slate swan im making automeme cmd so i get the link randomly and it needs to be set as image in an embed , how to do it
just use the image url?
embed.set_image(url=)
okk
homotrollius, there is no discord.Guild.member but it seems like discord.Member.guild is what I need.
member belongs to a guild
member.guild is the guild that the member is in
huh
as I've said before you can use guild.get_member(id), which returns not a nickname but a member object
another error 

A member is in a guild, a guild has many members
Not rocket science
put an if for each unit and input them to the db in the hour:day:month:year format
async def change_pfp():
print("Pfp changed")
with open("pick.png", "rb")as image:
print(type(image.read()))
await client.user.edit(avatar=image.read())```
Why I get Unsupported image type Error ?
code
And I can get display name through the member object?
??
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Downloading/streaming music from YouTube breaches their terms of service
ok tq for remembering me
so my friend has his own dsc bot, it uses yt-dl to play music, so does that violate youtube's ToS
yes
Yes
why is there nothing that happens to my friend's bot, like get a warn
Because it's not popular
If I use wavelink am I breaking tos?
Not getting a warn doesn't mean it's allowed to
If you're downloading/streaming, yes.
πΆβπ«οΈ
And I'm pretty sure lavalink does that
that means every bot in dsc that plays music is breaking yt's tos?
No
1: They might play local music
2: They might play from a service that allows streaming/downloading
3: They are in contact with and YouTube allows them that (really doubt though)
are there any resources that my bot can use to play music without breaking laws
Search on internet if there are music services that allows streaming (or downloading) music
how do i check if a specific user has been pinged in an on_message?
ive tried
@commands.Cog.listener()
async def on_message(self,message):
dontbepinged = self.bot.get_user(746384558831698012)
#cluser = 746384558831698012
if dontbepinged.id in message.content:
print("pinged")
await message.channel.send(f"pong")
and
@commands.Cog.listener()
async def on_message(self,message):
dontbepinged = self.bot.get_user(746384558831698012)
#cluser = 746384558831698012
if dontbepinged.mentioned_in(message):
await message.channel.send("pong")
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
easy
π€ do i have to get_member instead of get_user?
if message.content in "<@!<theird user id>>":
get member is used with a guild id
using this
thats the opposite of what you need lol
wait wha?
its like py if 'apple' in 'a':
he wanted the bot to respond back if someone the specific user gets pinged right?
ye it should be the other way round no?
message.content returns the message , so you mean they would be using py if 'the message' in 'bot\'s mention':?
i am terrible at english
yea py if bot.user in message.mentions
would work
!d discord.ext.commands.Bot.user
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
bot.user would be the bot right? so if i want to see if im being pinged, i would do
dontbepinged = self.bot.get_user(746384558831698012)
if dontbepinged in message.mentions:
yea it would work
!d discord.Member.mentioned_in exists bro....
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
if that's your id
its true even if someone pings everyone/here or role xd
you are creating a selfbot ?
nu
or am i wrong?
no
Okay
No?
self means a Cog class here
Is it tho?
no i mean selfbot for the id
just making it so that everytime im pinged it gets sent to another channel so its easier to find
isn't selfbot against the tos?
Then just do if len(role.mentions) ==0
wouldnt that make it so all the pings are sent ?
yea but its not a selfbot
just want it to be specific to me
@commands.Cog.listener()
async def on_message(self,message):
dontbepinged = self.bot.get_user(746384558831698012)
if dontbepinged in message.mentions:
print("pong")
await message.channel.send("pong")
``` also this isnt working, am i supposed to get member instead of user?
do you have member intents?
yep
Oh, hmm... Weird implementation then
gimme a minute , ill test it
ive tried dontbepinged = message.guild.get_member(746384558831698012) too
ok so dont mind the way i get the message object , but this seems to be completely applicable
is the cog loaded?
try printing something when the on_message takes place to make sure that its really triggered or not
the self.bot.get_user part could be None . but i dont think so that its the problem since you might for sure be sharing a guild with your own bot
i think is self.message and not self,message
i dont think its self.message in the on_message π€ everything else in the on message works except the ping
can you check your intents again in the code please
and does get_user(746384558831698012) actually return a value or None
intents are intents = discord.Intents.all()
implied inside commands.Bot too?
yep
and this thing
it returns None
yes π€
hm , well you can use py if '@arctic vapor' in message.content:
the point that bot's returning None even with member intents is weird tho
ahh sweet got it
yea idk why, it was working a few months ago so i was confused now
It returns None because the member is not in cache
So you got to use something like
x = get_member(id) or await fetch_member(id)
So that it tries to get the member from cache (get_) and if it returned None it makes an API call (fetch_)
the user is bot's owner itself who for sure has a mutual guild with the bot
Caching has nothing to do with mutual guilds...
member intents are enabled too
then it does
for sure does
Yeah no shit Sherlock
But it's not because the user shares a guild that it's obviously in the cache, that's my point

makes sense
!d
Anyone know how to get the string after a option on slash commands? So like
/userinfo name: Hatsune Miku and when you print that the output is
Hatsune Miku
depends on the library u r using
discord-py-slash-command alongside discordpy
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = None
self.bot.loop.create_task(self.connect_database())
async def connect_database(self):
self.db = await aiosqlite.connect("main.sqlite")
@commands.command()
@commands.cooldown(1, 3, commands.BucketType.guild)
@commands.has_permissions(administrator=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
async with self.db.execute(
"SELECT count from 'totalcases' where guild_id = ?",
ctx.guild.id,
) as cursor:
config = await cursor.fetchone()```
```py
Command raised an exception: ValueError: parameters are of unsupported type``` whats wrong?
ctx.guild.id must be inside a tuple
option.value iirc
?
<the variable for your option>.value
Anyone able to help me out
Depends
Ignoring exception in view <SpotifyView timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='More Info!' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\cwals\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 365, in _scheduled_task
await item.callback(interaction)
File "C:\Users\cwals\Documents\GitHub\proxy-testing\cogs\views\views.py", line 40, in SpotifyButton
if self.member.activities[1]:
IndexError: tuple index out of range
if self.member.activities[1]:
embed = discord.Embed(
colour = self.member.activities[1].colour,
title = 'Activity Information',
description = "This task was completed without any errors."
)
The tuple index is out of range, try 0
Iβm trying to make a system, where I can store a gameid and 3 players for 2 teams.
I first thought about making 2 dictionaries, both with the same gameid as a key, and the players as the values.
Would there be a more efficient way to do this?
So like, an activity status ID?
here's my thing, i'm checking if there's a spotify activity in the tuple, but if it isn't there it is only [0]. how do i fix it?
Might want to check the web for that, I am not sure.
How do I make the bot delete every message that gets sent to the specific channel but it still gives the role to the user when they do the command correctly? Itβs for my verify command
@client.event
async def on_message(message):
if message.channel.id == 909671265864933406 and message.content.lower() == '*verify':
fullaccessrole = get(message.guild.roles, id=909670961115201537)
await message.author.add_roles(fullaccessrole)```
async def command(ctx , option : str):``` so you have something like this in your slash command?
Yes, I already have everything I'd need for slash commands except for getting the value of user input
the option variable would be the user input value ...
Tell me how to make sure that the penultimate line every 60 seconds finds information about the remaining time of the participant's mute, and the last line takes 60 seconds every 60 seconds, and when the penultimate line displays information that there are 0 seconds left, the cycle stops and the mute is removed from the person
and you would be having options from the decoratorpy @slash(options = [])
@client.event
async def on_message(message):
if message.channel.id == CHANNELID and message.content.lower() == '*verify':
await member.add_roles(discord.utils.get(ctx.message.guild.roles, name = "ROLENAME"))
await message.purge(limit=1)``` This should work
I already have all of this, I just need to get the user input from an option.
well the gameid is just an integer that increases by 1 whenever my queue of players reaches 6/6
is there anyone familiar with dislash.py?
Alright, I can set up a global wide example real quick
tyvm
?
Afk for a sec
@client.command()
async def joinq(ctx):
listname.append(ctx.message.author.id)
if listname.len() == 6:
await ctx.send('Added you to queue, 6/6')
#additionalstuff
if listname.len() > 6:
await ctx.send(f'Add you to queue, {listname.len()}/6')
``` This should work
Really simple queue though
Iβm sorry I donβt think I explained myself correctly
Iβm wanting to store the playerβs in the queue and working out what teams they are on, and link them with a game id
We can split them out into teams with a random function
How to make a loop so that every 60 seconds these two lines work
Not sure
right, but then where are the player id's and gameid stored
for each team
for context btw, this is my q command:
@bot.command(pass_context=True, name="queue", aliases=["q"], description="Join the queue")
async def queue(ctx):
if ctx.channel.id in allowed_channels:
ggid = settings.find_one({"guild_id": ctx.guild.id})
game_id = ggid["game_id"]
pid = ctx.author.id
pmention = ctx.author.mention
if pmention in playerqueue:
embed = discord.Embed(
title=f"{ctx.author.name}, you are already in the queue",
color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
if pmention not in playerqueue and len(lobby) < qsize:
playerqueue.append(pmention)
lobby.append(pid)
info = pstats.find_one({"id": pid})
if info is None:
newuser = {"id": pid, "Wins": 0, "Losses": 0, "MMR": 1600, "Rank": "C"}
pstats.insert_one(newuser)
embed = discord.Embed(
title=f"**{len(playerqueue)} of {qsize} players are in the queue**",
description=str(ctx.author.mention) + " has joined!",
color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
if len(lobby) == qsize:
games[game_id] = lobby.copy()
lobby.clear()
playerqueue.clear()
game_id += 1
settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
embed = discord.Embed(
title=f"**The queue reached {qsize} players**",
description="Voting is now underway!",
color=0xE74C3C)
embed.add_field(name="Vote for random teams", value="!r", inline=True)
embed.add_field(name="Vote for balanced teams", value="!b", inline=True)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
I cannot help as much as far to store the gameid right now
But, you can do something like find a random game id and check if it isn't occupied and then create a new list with the teams in them
@client.command()
async def joinq(ctx):
x = random.randint(1, 2)
if listname2.len() > 6 and x == 2:
listname2.append(ctx.message.author.id)
#additionalstuff
if listname1.len() > 6 and x == 1:
listname1.append(ctx.message.author.id)
)```
Most basic way I can think of right now ^^
Don't have time to make a full out queue list right now, so I made the basic one I can think of
all g yeah, thanks for your help
How to make a loop so that every 60 seconds this line:
self.mutes.update_one({'member_id': member.id}, {'$inc': {'time_unmute': -60}})
Removed 60 seconds from mute time
And this:
unmute_time = self.mutes.find_one({'member_id': member.id})['time_unmute']
Checked how much time was left
Help me please
the discord.ext.tasks extension might be what you are looking for
Sorry, but how can I use this?
it allows you to run a loop every x seconds, and you can also find out how much time is left until the next iteration
That doesn't really help
I've done set out an example of what I want to do
Any errors?
Mhm
Information is in the pins
!pypi disnake
nopr
Alright, a few questions
Is it just not showing up in the commands list?
So it's just not showing up in the slash list at all?
nope
oh okay
Make sure you enabled intents for your bot and set them to all in the code, and then make sure you invited the bot with more than the bot, let me check and see what else needs to be enabled
uh i dont have the intents
Yea also make sure u have application.commands scope
No worries, no need for those
And the best solver for this issue for me was guild_ids = [YOURGUILDID]
yes but if i want to do this in all the servers?
Yups. But idk if that's test_guilds or guild_ids since the kwarg differs from lib to lib π
Then don't set it and wait for 2 hours
You'll need to wait for it to all register
Anyways, you mind helping me? I am just trying to figure out how to get the input for an option, so like
/userinfo name: Hatsune Miku and if we was to print the input from it it'd return Hatsune Miku
Which lib?
discord-py-slash-command
thinking of pulling xbox and Spotify connections, this embed is pretty as it is, any suggestions? wether i make a separate cmd, a second embed, idk what to do
Sorry never used that. Mind sending the docs link here?
This is good tbh
I am not sure if there is an official documentation for it yet
doesnt really answer the question..
Lemme see what I can do. Gimme 1
Alright
"wether i make a separate cmd, a second embed" is what I answered to
so just leave it?
Wait u wanna get the Spotify and Xbox connections, right?
mhm
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the userβs hash.
str(x) Returns the userβs name with discriminator.
yeah ik how to get it
Ignore this
thats easy, but what im trying to figure out is wether i should put connections in the same output message, but a separate embed
or just a separate command all together
same message separate embed
yay more writing :D
this command took 2 minutes to learn what to do, and an hour 34 mins to write it
π
pages eeee
It is easy to make
i can see how id do it
but ive never rly learned
would love to tho, dk where to start
Well I can help u to make a paginator with buttons if u want
sure, im on mobile rn and my eval command pooped itself when i updated to v2
so testing a cmd wont be too easy
I'll give it a throw
Haha well are you familiar views and buttons?
nope, my command that lists perms is 300 lines btw
Sure
i doubt that the way i went about it was smart
Oh well I can tell u basics about it if u want
π
if user has this perm:
emote is this
if user does not have this perm:
emote is that
BTW an easy way to make that embed would be
did that for all perms π¬
perms = ctx.author.guild_permissions.items()
for perm, value in perms:
embed.add_field(name=perm, value="true emoji" if value is True else "false emoji"
await ctx.send(embed=embed)
That will iterate through each permission and add an embed field
Tf
does that just compress 300 lines of source...
did i really type 8.4kb of a command-
I don't care about kb but the lines and that work 

Lmao
this returns a value tho doesnt it
wym
like administrator : true, send message : false...
No
It will see if the value is True or False
The value of the field will be true emoji if True else false emoji
eek yk what i did for the embed
embed = discord.Embed(description=f"
General Server Permissions\nView Channels: {viewchan}\nManage Roles: {marl}...")```
basically, typing on phone is so hard especially when writing py
True
Welp
Also
Just do perm.title() to change the case
!d str.title
str.title()```
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
For example:
```py
>>> 'Hello world'.title()
'Hello World'
``` The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
```py
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
```...
eek
Ok this works, thank you.
Cool!
Hi can anyone explain me how can I make my bot detect if I tagged someone?
Example:
e$user[@example_User]
Bot returns:
example_User data
How to make the condition that if there is nothing in the collection, then stop the loop
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
!d len is what u r looking for, ig.....?
len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
What to do, please tell me
Wait u wanna check if mutes are 0?
When I issue several muts and they end, this error appears and I wanted to disable the loop when there are no active mutes
Just use a try except, ig? I never used that module so cannot help you with this one, sorry
Good, thanks
the break keyword exits a loop
But not sure about @tasks.loop
It most likely has a stop method as well
yo anyone know the code make a discord bot dm people with a specific role
trying to ping people for a event
ive been trying for the past week and got nothing
plz help
Loop over your guilds members, check if the role is in the members role. If so, dm them π€·
ok ill try that
How to i use process_commands
Send code
it worked like 2 weeks ago
idk if its cause discord.py isnt a thing anymore
It's because there is no member
@tasks.loop(seconds = 30)
async def staffrolesloop():
mainguild = client.get_guild(884780660856881152)
staffguild = client.get_guild(900459740063207464)
staffrolesinmain = [884780660869447768, 884780660869447767, 884780660869447766, 884780660869447763, 884780660869447762, 884780660869447761, 884780660869447760, 884780660856881161, 884780660856881160]
staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467437273772134)
for g in mainguild.members:
memberid = g.id
for i in staffrolesinmain:
role = discord.utils.get(mainguild.roles, id = i)
if role in g.roles:
member = staffguild.get_member(g.id)
await member.add_roles(staffroleinstaffserver)
else:
None
@tasks.loop(seconds = 30)
async def staffhqstaffrolesloop():
mainguild = client.get_guild(884780660856881152)
staffguild = client.get_guild(900459740063207464)
hqrolesinmain = [884780660869447763, 884780660869447762, 884780660869447761]
staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900501559027331082)
for g in mainguild.members:
for i in hqrolesinmain:
role = discord.utils.get(mainguild.roles, id = i)
if role in g.roles:
member = staffguild.get_member(g.id)
await member.add_roles(staffroleinstaffserver)
time.sleep(1)
else:
None
@tasks.loop(seconds = 30)
async def hqstaffrolesloop():
mainguild = client.get_guild(884780660856881152)
staffguild = client.get_guild(900459740063207464)
staffhqrolesmain = [884780660869447767, 884780660869447766, 884780660869447763]
staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467350179033120)
for g in mainguild.members:
for i in staffhqrolesmain:
role = discord.utils.get(mainguild.roles, id = i)
if role in g.roles:
member = staffguild.get_member(g.id)
await member.add_roles(staffroleinstaffserver)
time.sleep(1)
else:
None
@tasks.loop(seconds = 30)
async def managementrolesloop():
mainguild = client.get_guild(884780660856881152)
staffguild = client.get_guild(900459740063207464)
managementrolesmain = [884780660869447768, 884780660869447767, 884780660869447766]
staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467392122069043)
for g in mainguild.members:
for i in managementrolesmain:
role = discord.utils.get(mainguild.roles, id = i)
if role in g.roles:
member = staffguild.get_member(g.id)
await member.add_roles(staffroleinstaffserver)
time.sleep(1)
else:
None
there is tho, theres 100 members in the discord
discord.py is still a thing they just aren't updating it
theres 100 members in my discord
i'm confused
it syncs 2 servers roles
it's because member is None
"NoneType"
there is members tho
@slate swan what could it be
It says right here that member is none so no member is being defined.....
there is members in both servers
could it be todo with intents
Try using jishaku
what is it
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
?
How to correctly check if the collection contains at least one element
in an on_message event?
from discord.ext import commands
bot = commands.Bot(commands_prefix='o!')
@bot.commands()
async def yur(ctx):
await ctx.reply('yesirrrr')
bot.run ```
why it aint working?
Remove the s in bot.commands
@slate swan
tried still dont work
And
Fix your indentation
?
Bot.run
Unindent bot.run and it should be bot.run('your token here')
is it possible to make a command add command?
How to check if a collection is empty or not? (mongodb)
How can I display the data written in my json file?
I tried doing a for loop but it didn't seem to work for it
with open('file.json', 'r+') as k: data = json.load(k)
Already done but I'm getting confused at the loop part
and you can do print(data)
what are you getting confused about?
can you say what you need help with? just came
data returns a dict. You can go through dicts like a normal dict
for k in data: print(k)
oh
I have
for data in data['users']:
yes = data['id']
Etc like that but it's not working
Looks unidented because I wrote it
in a loop, you cant give the name to the data
so try py for k in data['users']: yes = k['id']
you can also print(data)
i trying to make a bot that dm people with a certain role its for a event server i host
Ok one sec
Okay, and what has gone wrong?
Gives "the json object must be a str, bytes or bytearry, nor TEXTIOWrapper" do I need to import stringIO?
can you show the code?
@client.command()
async def showquote(ctx):
with open('quote.json', 'r') as f:
data = json.loads(f)
for f in data['users']:
yes = f['id']
yes3 = f['username']
yes1 = f['time']
yes2 = f['quote']
embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
await ctx.send(embed=embed)β
Gives keyerror 'id'
give me a min
well clearly 'id' is not a key within data['users'][f]
so you might consider print(f) to see what keys there might be.
maybe you do not need the for loop?
It works then it shows everyone perfectly
you're welcome.
well by using basic python. are you sure you understand this code. you are using the <= operator rather than >. you can just use a simple bool check for this also. since if it is empty it would return None
If I didnβt understand this code, I wouldnβt write it, but I want to try your version, please tell me how to execute it?
well if it couldnt find_one why would you need to check that the collection has one element
then you can explain why you are using <= operator
Sorry this might be dumb but it's still not working it did print everything but how do I get it to show in discord I did "yes = f['id']" but it still doesn't work
I need to check using the condition - is there at least one record in the collection, if there is, then the cycle will execute it, if not, then it will stop
the what
I do not use - <=
i dont know what you are trying to do but if the code you are looping through above the screenshot is a collection that is a list
I do the command mute and when I issue one line, which takes away -1 every second and thus, when the time is over, mute is removed
erm interesting lmao..
tell me what self.mutes is raw
yes is self.mutes = mycluster["something"]["something"]
yea
I'm a beginner, so I write this way
this is not beginner code
which im asking because you are asking a beginner question
but netherless.
good
if self.mutes = col["something"]["something"]
then just use
collection = list(col.find())
and check that the list is not None
i still dont understand your code and you wont tell me what i want to know so thats the best i can do
Is it embed instead?
like i said. i still dont know cuz you wont tell me what self.mutes is raw
I told you that this is a collection
and ive told you 2 different ways. how can you write all this mongo code and not know how to check if the collection has an element in it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
just loop through your collection and do a simple counter to check that its more or not 0
so?
this isnt your code lmao
Believe it or not, I just didn't learn python right away, but started practicing
Otherwise, how did I create a database and collections according to yours?
questions = [
'Question1',
'Quesiton2',
'Question3',
'Question4',
'Question5',
'Question6',
'Question7',
'Question8',
'Question9',
'Question10'
]
@bot.command(name='apply')
async def name_here(ctx):
await ctx.reply('attention', mention_author=False)
await ctx.author.send('text here')
await asyncio.sleep(10)
# Gen 'questions' randomly without repeating
i wanted the bot to generate these strings (questions) randomly, but without repeating. Example: [1,1,2,3,4,4] any1 can help me?
code: py time2 = t.total_seconds / 60
error: unsupported operand type(s) for /: 'builtin_function_or_method' and 'int'
please help
check what t.total_seconds is
counting time
t = timedelta(days = 30 - datetime_object.day, hours = 0 - datetime_object.hour, seconds = 0 - datetime_object.second , microseconds = 0 - datetime_object.microsecond )
no what does it return
but by the way u used microsecond attr i imagine its a float. in that case you should of learnt basic python as you would know to use // operator
error like this: <built-in method total_seconds of datetime.timedelta object at 0x7fa730239270>
still not what i asked
this is the code
what are u trying to do
you ask for this:
t = timedelta(days = 30 - datetime_object.day, hours = 0 - datetime_object.hour, seconds = 0 - datetime_object.second , microseconds = 0 - datetime_object.microsecond )
print (t.total_seconds)
respone: <built-in method total_seconds of datetime.timedelta object at 0x7f83a9b60150>
total second is seconds calculating by this code
just format it to a string
How to add mute role to all channels when the command is activated
right now its just calling the function
what do you mean. into the permissions?
Well, you can say so, like a JuniperBot, when someone was muted, the role was added to all channels
just use discord.TextChannel.set_permissions(role,*permissions=[bool])
okay, thanks
Ik this isnβt code related but what do yβall use for hosting?
i need suggestions for what to do on the second page. i wanted to do connections but discord doesnt provide that data to bots
who cares its your bot do as you please
out of ideas
you can work with discord.Member.guild_permissions
ok we dont give u ideas here we just help run ur code
yes we help run ur discord-bot code
im trying to get my bot to dm people with certain role
roles? permissions general info(id, and such)
ok check that your role object is in those member.roles
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the memberβs guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
i forgot how to do that have not use python in a long time
how ever you gain your role obj
if role_obj in member.roles:
but if i do that will the "questions" be repeated?
no? its going to pick one random element in that list
targex = omega.get_channel(int(chanid))
await ctx.message.delete()
async for message in targex.message.channel.history(limit=None).filter(lambda m: m.author == omega.user).map(lambda m: m): ```
Targex comes from the function args. It returns "targex has no value 'message'"
targex is already a channel
but targex.history doesn't work either
await flatten()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Flattens the async iterator into a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") with all the elements.
oh wait, youre iterating it with async iter
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'history'
Wait it worked, I was using dm channel π

Anyone know how I fix this?
the syntax is as the following: for <var> in <iterable>:
No clue what that means lol
Nvm I fount the mistake lol thanks
Please tell me what this means? I register the command and now
Yes lmfao
I wouldn't use it if I were you
Iβm following his βmake a botβ rewrite trying to learn
I need a unban command lel
Aye I fixed it
Hi guys anyone know how to only βactivateβ a command when 3 people who use it say it?
Why doesn't the bot add role permissions to the channel and how to do it so that if the rights for the role are already set, then nothing needs to be done
Hi, i want to make a command that shows the renaming cool-down of all other commands. what should i use? is there any default methods to check?
When I try to add a role to all channels and issue prpva, this error appears
Are you sure speak is a valid permission?
yea
Just indent it bruv
iirc its Speak with a capital S
Returns True if a user can speak in a voice channel.
I see thx
https://mystb.in/EntranceTriedFish.python
no errors, even with the exception that prints the error. the embed sends, i can use the button once to go to the next page, and then the command just dies
not sure why
What do you mean by say it?
could I ask for help with a problem?
Sure
I want to have a while true loop which checks if a certain event happens and if that event happens, it should send a message to a specific discord channel. Now I coded some bots already and I know how the basics work, but how could I "build" this? I couldn't do it in a task because it is supposed to stay in the while true loop permanently
while True:
response = recv(sock, 1024)
pprint(response)
if (response == "PING :tmi.twitch.tv\r\n"):
send(sock, f"PONG :tmi.twitch.tv\r\n")
continue
if (substring in response):
sendmessage(response)
def sendmessage(response):
await channel.send("Text")
It should work like this
ah I think I know how I could do it, I could ask a command to trigger that while loop, I wont be able to start a new command but that wont matter
How to change bot status (not activity) using python
Anybody know a good buttons tutorial for disnake i have no idea where to start and docs werent to helpful
I recommend using discord-py-slash-commands library, its easy and disnake is new so IDK about it. Heres the docs https://discord-py-slash-command.readthedocs.io/en/latest/
Thx but im just looking for a disnake buttons tutorial
!d discord.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
β’ [`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")
β’ [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
!d discord.ActivityType
class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity"). This is used to check how to interpret the activity itself.
thats exactly what i pointed you to ^
I think he or she ment by like dnd and others
Its like watching, plqying
not actually
again, exactly what i pointed you to.
Huh
^
^
Yes you can in the dev portal
in your developer portal, the description is the about me
No in the dev portal
this was what I mean
o ok
Bots don't have access to this custom status
Your bots about me needs to be changed in the the dev portal
\π
You can use playing ig it just says playing:
Whats the matter with that?
Nah Nah I was just thinking
Alr
how to fix this bug in typing.py? I'm newbie and trying to make my first bot but module errors is...
?
So do y'all know how one of the features you can do with Discord is copy the link of images and then when you copy the link it gives you https://cdn.discordapp.com/yadayda Is there a way to do that but with Discord py? I'm trying to take the user input of an image essentially.
I tried to search up the way to do it, but I haven't gotten any luck.
Here's my code for trying to get a user's image:
4th field
def check4(msg4):
return msg4.author.id == member.id and msg4.channel == channelawait channel.send("Any screenshots? If you do, paste in a link to the screenshot (i.e. imgur.) If you don't type None")
try:
msg4 = await client.wait_for('message', check=check4, timeout=120)except asyncio.TimeoutError:
await channel.send("You didn't reply in time.")
guild = member.guild
await channel.set_permissions(member, send_messages = False)role = discord.utils.get(guild.roles, name='InReports') await member.remove_roles(role)
my new lines aren't working and I can't seem to understand why
send your code.
How do you get an authors permissions?
I know ctx.author.roles exists
I'm not sure ctx.author.permissions exists Lol
w
hm
I pull a string from an API and then I just send it in an embed description, other things like backtick text or bold text render but not \n
no need to show code
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberβs hash.
str(x) Returns the memberβs name with the discriminator.
checked that already
appreciate it
!d discord.Member.guild_permissions
property guild_permissions: discord.permissions.Permissions```
Returns the memberβs guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
snow do you have any idea why?
im really not sure, as far as im aware if your \n is inside the string it should add a new-line.
I thought so too
@agile shadow you can use guild_permissions
sure
Is this possible?
@worthy wagon
iterate through ctx.author.guild_permissions using a for loop.
yep!
this may be quite far fetched, or is it because im doing news = news.replace('"', "")
that shouldn't affect anything though because its already in a string
does anyone know a decent api or how i could fetch tiktok profile data? including followers, following, likes etc
thanks
there's also, https://github.com/avilash/TikTokAPI-Python
??
it says 723 lines
Ah
Those are the lines from the library
Then how can i do it str?
f"**{Emoji.CHECKMARK} Here are all my modules!**\n\n__**{Emoji.NOTIFICATION} {bot.user.name} News**__\n{await get_latest_news(latest_news_id)}"``` @patent lark do you see anything wrong in this?
json["token"]
Why is their 2 \n?
Nvm you want to do 2 new lines prob
Isnt that just one line? of space
it is a string
so the \n should be intepreted
Yeah ik lol
what I don't understand, is why the \n isn't doing anything
Nvm i know what you mean now
Are you using an embed?
yes
Ah
@agile shadow try making a list and use "\n" .join() i think its like that
what
Basically gets a list and for each string it makes a new line
that's not needed
Spaces in embeds are weird. If you wanted a bigger space in an embed, you will have to use a blank character, which is chr(173). Idk if that helps, or is what you want. \n will not work the way it's supposed to on embeds.
how do I get chr(173) ?
that's the blank character
Your making a embed and \n isnt working i recommend using that method
so having a field of just chr(173) will make the space.
For example:
embed = testembed.add_field(name=chr(173), value=chr(173))
Hopefully that helps, the space may be too big though.
let me try
actually, @ornate glade I want to understand first why the first \n\n and second \n worked, but not the rest
Ah, I know why, it's because the \n isn't being intepreted, it's like I'm doing
""\n""```
I think if you add a space between the 2 \n it wont have the same indent level
Huh?
I don't know how to say it, but it's like I'm not using the string in a way where \n would be applied
Is the problem fixed though?
yes, but I'll have to do some refactoring to how I get that string in the first place, I was pulling it off an API but that might have to just be a local file or something I update periodically
Yeah like if it was a str
yea
why not ask in your fork's support server
I dont have one?
https://github.com/DisnakeDev/disnake theres an invite link to disnake's support server here
and disnake is a fork of dpy wdym
I know it is
Dont quite know what you ment there
About what?
@agile shadow Did this worked or how did you fixed it?
In my wrapper, should I dispatch user: lefi.User to READY event callbacks or just make users access the client's user through lefi.Client.user
click on any of those buttons, theres an inv link
Thx
latter
Any specific reason?
I'm only dispatching it right now as I get it from the gateway after parsing everything
there isn't really a reason to pass it considering they can just access it from their lefi.Client instance
in my opinion at least
Wouldn't it be more verbose to make users use it through the first way as either way, lefi.Client.user would be None until READY is recv'd from the gateway
This is mostly a design choice though, I don't really care where it can be accessed or at what time
Current examples look like ```py
@client.on("ready")
async def on_ready(_: lefi.User) -> None:
print("logged in")
And it's sort of bothering me as lefi.Client.user is also there
Hey, how can i add my pc stats to bot stats?
ram usage, processor usage, operating system infos and stats
Essentially I am working on an auto softban that bans members that type in a certain channel, and have less than 2 roles. The code I have is
if message.channel.id == 909685766244945921:
print('Nerd')
if len(message.author.roles) <= 2:
print('Bozo')
await client.send_message(message.author , 'You have been softbanned due to falling for an obvious trick... (nitro scam)')
await message.author.ban(reason = 'You typed in the kick channel!')
await message.guild.unban(discord.Object(message.author.id))
The print statements are for troubleshooting purposes, dont mind them. I am getting an error after I added the client.send_message line. the error is
AttributeError: 'Bot' object has no attribute 'send_message'
is that the on message wvent
Yes
event*
await message.author.send(...)
so to send messages in a channel, first you have to get the channel object of it, message.channel
your code has been invalid since v1
Ah so these internet people suck
understandable, thank you
were you expecting us to spoonfeed
they always have. Tutorials / Stack Overflow isn't great. its always outdated shit lol.
Best is to see the docs and official examples.
Docs https://discordpy.readthedocs.io/en/stable/
Examples https://github.com/Rapptz/discord.py/tree/v1.x/examples
Tbh thats the first time Ive ever been mislead, big scam. But Ill bookmark the docs, thank you
no prob :DDD
Hello, I'm having a problem I'm not able to show the data stored in my json file
@client.command()
async def showquote(ctx):
with open('quote.json', 'r') as f:
data = json.loads(f)
for f in data['users']:
yes = f['id']
yes3 = f['username']
yes1 = f['time']
yes2 = f['quote']
embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
await ctx.send(embed=embed)β
``` that's the code but it gives keyerrors and when I just try "print(f)" it shows the data in there can someone help
its giving me this error when i use tempmute command
the error:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "time".
and the code:
@client.command()
async def tempmute(ctx, member: discord.Member, time: int, d, *, reason=None):
guild = ctx.guild
for role in guild.roles:
if role.name == "Muted":
await member.add_roles(905765835791036477)
embed = discord.Embed(title="Muted!", description=f"{member.mention} has been tempmuted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
embed.add_field(name="time left for the mute:", value=f"{time}{d}", inline=False)
await ctx.send(embed=embed)
if d == "s":
await asyncio.sleep(time)
if d == "m":
await asyncio.sleep(time*60)
if d == "h":
await asyncio.sleep(time*60*60)
if d == "d":
await asyncio.sleep(time*60*60*24)
await member.remove_roles(role)
embed = discord.Embed(title="Unmute (temp) ", description=f"Unmuted -{member.mention} ", colour=discord.Colour.light_gray())
await ctx.send(embed=embed)
return
Your code is good you're supposed to say it like this "tempmute [user] [time] [duration] [reason]"
like this "?mute @hushed siren 1 d Test"
Yes
okay ill try
Also you wrote "if role.name =="Muted":" you don't need that part since you added the role ID you want to give
It's just "discord.version" no need for the brackets
Ignoring exception in view <UserInfoView timeout=15.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='View More Info' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "c:\Users\user\Desktop\theBot\cogs\misc.py", line 201, in receive
await interaction.response.send_message(embed=success_embed, ephemeral=True)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 526, in send_message
await adapter.create_interaction_response(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 191, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.description: This field is required
```i have this error, i ran the command on someone who only has the @ everyone role
```py
if len(self.member.roles) == 1:
pass
else:
yourRoles = ', '.join([role.mention for role in reversed(self.member.roles[2:])])
success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)
i even did ```py
# checks member's roles
if len(self.member.roles) == 1:
print("member doesnt have any other roles beside @everyone")
print(self.member.roles)
await interaction.response.send_message("done")
return
else:
yourRoles = ', '.join([role.mention for role in self.member.roles[2:]])
# success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)
print("member has other roles other than @everyone")
print(self.member.roles)
await interaction.response.send_message("done")
return
and what it printed was:py
member doesnt have any other roles beside @everyone # on someone who only has @everyone
[<Role id=879311327720538142 name='@everyone'>]
member has other roles other than @everyone # on myself
[<Role id=879311327720538142 name='@everyone'>, <Role id=879573209203236906 name='verified ββ . ΰΉ*q'>, <Role id=883893045781729310 name='admon'>, <Role id=902489063368589323 name='bot mod'>, <Role id=896652444916924416 name='donkvolopers'>]
Embed's description is None
Can you show your entire code
isnt description optional
it worked perfectly fine previously with 1 field but without a desc
If u wanna make it optional, then don't add the description kwarg.
i didnt
Is there an error in console you can show
Well try printing the embed
wdym
print(embed)
no error
Remove the error handler you have or make an else statement and type "print(error)" in the statement
<discord.embeds.Embed object at 0x000001DCB811C820>```
Okay
Try doing print(str(embed))
hello, im new to discord bot(coded by python), is replit.com ok for coding bot?
<discord.embeds.Embed object at 0x000001EDCE547820>```
For basic coding, sure
then where should i start?
Tf... Try doing dict(embed)
print?
Ye
!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.
Okay... Gimme 1, lemme tell you what to do
Try doing
yourRoles = ','.join(role.mention for role in reversed) if len(reversed) > 1 else print("user has @everyone")```
Sorry code might be messy I'm on phone
Yea just do print(embed.to_dict())
Use a good IDE something like vscode
@maiden fable
nah idtt thats the problem
any video tutorial? if yes, pls dm
Any someone also help me?
Video tutorial for what?
{'fields': [{'inline': False, 'name': 'Roles [4]', 'value': '<@&883893045781729310>, <@&902489063368589323>, <@&896652444916924416>'}], 'type': 'rich'}
Well your embed does show it's empty so just try to dict your embed
video tutorial about coding discord bot using python
Just look it up bro
dont follow tutorials
You need to pass the embed object to the embed kwarg in send
send(embed=...)
ok, then where should i start. ive setted up the bot and gained the bot public key
Can someone also help me
thz
Therr is a few things like that
@maiden fable
You should be sending strings not other objects really
E.g bot would be bot.user.id if you wanted the id
Or you can do name for the bot's username
You dont need a good ide the python idle would do fine
Also bot sends 2 messages at the same time
https://vcokltfre.dev/ hope it helps
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.
I mean yeah you can code on a notepad if you want but I just prefer vscode
Python idle would do good if your knowledge level is about intermediate i do recommend a ide,vs code is great for starters as well but not needed if your a beginner
Can someone help me too I'm having a problem I'm not able to show the data stored in my json file
@client.command()
async def showquote(ctx):
with open('quote.json', 'r') as f:
data = json.loads(f)
for f in data['users']:
yes = f['id']
yes3 = f['username']
yes1 = f['time']
yes2 = f['quote']
embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
await ctx.send(embed=embed)β```
that's the code but it gives keyerrors and when I just try "print(f)" it shows the data in there can someone help
thz
hey im trying to make an custom prefix command the bot runs and stuff but when i try the command its giving me a error
File "main.py", line 22, in get_prefix
return prefix[str(message.guild.id)]
KeyError: '905126423902167041'
the line its giving me error in:
def get_prefix(client, message):
with open("prefixes.json", "r") as f:
prefix = json.load(f)
return prefix[str(message.guild.id)]
Yw
you're not getting an error its giving you the server ID
can someone suggest some APIs to use with a bot with get request? Not looking for anything specific
but the prefix didnt change
the function you made is only supposed to return with the server ID
the guild's ID isn't in the JSON/dict
Any good databases?
Depends really
How can i make changing status
ok
need for discord bots
What u need help with?
.change_presence(status=discord.Status.idle)
use this
replace idle with what ever u want
dnd or online or offline or idle
add it in on_ready function
need for discord bots
Deploy a server(ubuntu 18 version something I forgot), get the ipv4 for it, set it up, use filezilla to connect to the server and upload your files to it easy
i did not get u
A sec
yeaaa about that
Did you click on the quick connect or open the site manager button on top right
A task*
Left*
And you put the IP and user as root or whatever vultr gave you and you put in the password it gave you?
?
yep
im not getting any errors it just wont let me connect to the server
Status changing auto
lemme try
put .change_presence() in on_ready() function
anyone knows?
Still u r not understand me lol
^^
Nvm
No a task is better
its a status cycle.
just did this its still not letting me connect
π
why does this only happen to me
and if i remember correctly it is a task like Okimii is saying
You have to wait for the bots cache to be ready to change its presence
Is protocol as SFTP?
ye should i change it
i dont know about task. sry
how can I make bot messages an embed instead of text
No that's correct let's move to dms since this is discord bots only
on_ready() isnt a good way to change presence
Wdym?
then?
You make a task for that
wdym by task?
Can someone help me?
^^^ anyone knows
!d discord.Embed you need to define and embed and pass it in as the message instead of text.
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
i mean currently my bot returns text and it looks terrible. I have seen some bots return an embed or like a weird outline thing around the text. What is the command for that? If you see above the python bot didnt exactly return text
can you send what is printed?
βasyncβΒ βdefβΒ βstartup_functionβ():
βΒ Β Β Β β#Β WeΒ willΒ letΒ itΒ waitΒ untilΒ theΒ botΒ isΒ fullyΒ loaded.
βΒ Β Β Β βawaitβΒ βbotβ.βwait_until_readyβ()
βΒ Β Β Β β#Β NowΒ let'sΒ setΒ theΒ bot'sΒ statusΒ toΒ onlineΒ andΒ theΒ gameΒ activityΒ toΒ '!help'
βΒ Β Β Β βawaitβΒ βbotβ.βchange_presenceβ(βstatusβ=βdisnakeβ.βStatusβ.βonlineβ,Β βactivityβ=βdisnakeβ.βGameβ(βnameβ=β'!help'β))
β#Β Now,Β weΒ wantΒ toΒ knowΒ whenΒ ourΒ botΒ hasΒ startedΒ up.Β WeΒ willΒ useΒ theΒ 'on_ready'Β event.
β@βbotβ.βevent
βasyncβΒ βdefβΒ βon_readyβ():
βΒ Β Β Β βprintβ(β"LoggedΒ inΒ asβ\nβ"β,Β βbotβ.βuserβ,Β β"β\nβ"β,Β βbotβ.βuserβ.βidβ,Β β"-------------"β)
β#Β NowΒ let'sΒ makeΒ ourΒ startup_function()Β run!
βbotβ.βloopβ.βcreate_taskβ(βstartup_functionβ())
Example from: @dapper cobalt
@glass rock this is a embed is this what your refering to?
yes exactly
Their it is 
Sure one sec
If you are talking about getting your help command to print out an embed instead of a message you will need to subclass your help command
Basic code of a embed btw yes theirs way more fields in the class
await ctx.send(embed=embed)
Btw its just a example dont copy paste it if you dont understand it
ok ty
Yes
ty
Yw
Sorry for the ping @brittle ingot
{'users': [{}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:22 PM UTC', 'quote': ['deez nuts']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:25 PM UTC', 'quote': ['deez']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:26 PM UTC', 'quote': ['deez nuts']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:27 PM UTC', 'quote': ['deez']}]}
That's the print
`ye thanks https://python.plainenglish.io/send-an-embed-with-a-discord-bot-in-python-61d34c711046 i was looking at this
!paste
Never seen it but a good way to learn dpy is from: https://vcokltfre.dev/
Good tutorial and up to date
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.
link doesnt work for me for some reason
Try copying and pasting it to your browser
oof it refused to connect.
maybe its some firewall @slate swan is tere an alternative link
Your probably using a proxy or vpn or the website is blocked for you,note if your computer is from school or work it might have been blocked by the administrator.
drat
Yeah
!d discord.Embed @glass rock you'd need to create a variable using this to create embedded messages
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itβs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
@forest spear Your trying to fetch all information and put it into an embed? it looks like you are only defining the embed for one entry?
thank you
But it shows keyerror on 'id' and how do I put it all in the embed then?
you gotta index users first then id
its how python works
It just shows me more error lemme show you one sec
you don't have to, if you wanna access the id key you gotta index users first like ["users"]["id"] since users is a list
Yeah that's what I did it shows keyerror on users now
hm weird
this is what i came up with. Disclaimer its been months since i worked with Python and very rarely do i work with JSON in python. so hopefully someone can fix any mistakes:
@client.command()
async def showquote(ctx):
embed = discord.Embed(
title=" ",
description= " ",
color=discord.Colour.red()
)
with open('quote.json', 'r') as f:
data = json.loads(f)
users = data.users
for user in users:
embed.add_field(
name=f"{user.id} | {user.name}",
value=user.quote.join(', '),
inline=False
)
await ctx.send(embed=embed)
if you want to select a random one you should be able to run random.choice(users) assign that to a variable and use that variable to select the info from the randomly chosen quote.
users is a list, so you have to do,
["users"][1]["id"]
^
Lemme try it thanks for the help
Sorry but they both don't work give the error "the json object must be str, bytes or bytearry not TEXTIOWrapper"
{
"users":[
{
},
{
"id":663415559630880778,
"name":"CIA#2771",
"time":"Mon, 15 November 2021, 09:22 PM UTC",
"quote":[
"deez nuts"
]
},
{
"id":663415559630880778,
"name":"CIA#2771",
"time":"Mon, 15 November 2021, 09:25 PM UTC",
"quote":[
"deez"
]
},
{
"id":663415559630880778,
"name":"CIA#2771",
"time":"Mon, 15 November 2021, 09:26 PM UTC",
"quote":[
"deez nuts"
]
},
{
"id":663415559630880778,
"name":"CIA#2771",
"time":"Mon, 15 November 2021, 09:27 PM UTC",
"quote":[
"deez"
]
}
]
}```
hm
show code
with open('quote.json','r') as f:
data = json.load(f)
for f in data['users'][1]:
yes = f['id]
print(yes)```
Looks unidented but I wrote the code down so yeah
Sorry I wrote the code down on phone it's there on my PC tho
i feel like this is most likely a job for a database, not json
File "C:\Users\jackie\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\jackie\Desktop\yes_bot\bot.py", line 1766, in showquote
data = json.loads(f)
File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\json__init__.py", line 339, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\jackie\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\jackie\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\jackie\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: TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper```
indeed
it should be load
not loads
I find databases like SQL or mongoDB hard unless theres like a tutorial for literally every possible thing you can do with them
and you have sliced the list so the element f of the for loop are the key names as str
well using json is a double edged sword
sure it's easy but more times than not i'll come back and bite you later on
the thing here is
f is actually a string, each of the keys in the subdict you specify
so it panics when you ask for f['id']
How would I make an optional argument for a command?
E.g. the member uses !stats which gives them their stats, or they can do !stats @ user which gives the users stats?
def someFunction(arg1, arg2 = "I am an optional argument"):
# stuff
But doesnt that mean I have to make arg 1 = to something as default?
You do
but arg 1 is ctx
Wait so how do I do it? I put f(str['id']) but now it gives error "type object is not subscriptable"
only optional arguments need a =
you're probably looking to iterate over the users subdict
I kind of want something like this
@bot.command()
async def stats(ctx, member: commands.MemberConverter):
Usually how I would go about doing something like this, is set the default optional argument to None. And within the function, you can do something like member = member or ctx.author which basically tells python, "if the user didn't specify anyone for stats, use the person who ran the command's stats"
fyi you should be typehinting to discord.Member
no need for commands.MemberConverter
success_embed = discord.Embed()
# checks member's roles
if len(self.member.roles) <= 1:
pass
else:
yourRoles = ', '.join([role.mention for role in self.member.roles[1:]])
success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)
```so if i only have the everyone role - the bot will return this error: ```py
Ignoring exception in view <UserInfoView timeout=15.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='View More Info' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "c:\Users\user\Desktop\theBot\cogs\misc.py", line 201, in receive
await interaction.response.send_message(embed=success_embed, ephemeral=True)
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 526, in send_message
await adapter.create_interaction_response(
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 191, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.description: This field is required```but if i have roles other than @ everyone then the command will run successfully, not sure why
When I try to add a role to all channels and issue permissions, this error appears
I just want the exact same user ID to show up there as well
Hmm I get what you mean, but I am struggling to convert it to my code
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, member = None):
if ctx.channel.id in allowed_channels:
pid = ctx.author.id
info = pstats.find_one({"id": pid})
if info is None:
embed = discord.Embed(description="You have not played a game yet!", color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
else:
pwins = info["Wins"]
plosses = info["Losses"]
pmmr = info["MMR"]
rank = info["Rank"]
standing = 0
rankings = pstats.find().sort("MMR", -1)
for x in rankings:
standing += 1
if info["id"] == x["id"]:
break
embed = discord.Embed(
title=f"{ctx.author.name}'s stats", color=0xE74C3C)
embed.add_field(name="Name", value=ctx.author.mention, inline=True)
embed.add_field(name="Wins", value=f"{pwins}", inline=True)
embed.add_field(name="Losses", value=f"{plosses}", inline=True)
embed.add_field(name="MMR", value=f"{pmmr}", inline=True)
embed.add_field(name="Standing", value=f"{standing}/{ctx.guild.member_count}", inline=True)
embed.add_field(name="Rank", value=f"{rank}", inline=True)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)```
token is None
clearly not
Where is token
You obviously did something to an empty object
Remove the parentheses and try again
it should be
client.run(os.getenv("token"))```
go to secrets create a secret name it token and value it as your token
"description"
It does, install master branch or use a fork.
isnt it optional
You didnt enter a token
I mean yeah but it says In data.embeds.0.description: This field is required error doesnt lie. Maybe something else is causing the error?
your supposed to get the key
im not sure tho, it worked previously without a description
my brain it hurts i cant understand anything
not the token
@slate swan your supposed to do it like this
key = "your_token" #in the secrets tab
bot.run(os.getenv("key"))
nice
Regenerate your token
Basically if you add your actual token your defeating the whole purpose
Wdym
Theres clearly a comment saying "in the secrets tab"
No i meant in the .run
yeah multiple people told him that already
why not? My database stores people based off user id's. So if they do !stats @ user, it will not find them in the database no?
You have added intents but didnt enabled in developer portal
Idk how I can convert my member argument to an id
the error dont lie
^
also you literally leaked your token, better reset it real quick
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, player = None):
if ctx.channel.id in allowed_channels:
if player = None:
pid = ctx.author.id
else:
pid =
info = pstats.find_one({"id": pid})
pid = player.id
also py if player == None:
right, so if they mention someone in the player argument, pid would be there id
π π
and if they mention an id, it will keep it?
yea
alright tyvm
π π
Should use if x is none but ok
File "D:\6Mans\Main\mainwithdict.py", line 135, in stats
pid = player.id
AttributeError: 'str' object has no attribute 'id'
You need to convert it to a discord user object first no?
common sense; player is a stringβ¦
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, player = None):
if ctx.channel.id in allowed_channels:
if player == None:
pid = ctx.author.id
info = pstats.find_one({"id": pid})
else:
pid = player.id
info = pstats.find_one({"id": pid})
if info is None:
embed = discord.Embed(description="You have not played a game yet!", color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
...
wait wait
you have player=None
But you need to do
player:discord.User = None```
Convert it to a discord object first yes.
player i mean
right
Whatever you are calling it ye
You could move the info = line out of the if else statements
yea or it would not work
It's common in both cases and hence there is no point making python process it twice
I tried but before but got an indent arror
