#discord-bots
1 messages · Page 901 of 1
If the user you want to ban is in the server, then the code is fine,
If not then you need to take in user id and convert it to user obj via fetch_user
You need to typehint user to discord.User
its because i want to blacklist people there isnt in my server
with blacklist i mean, do so they cant use my commands.
That's why you're type hinting it to a user object and not a member object
can you please change the code for me, i dont know what you mean
No
We're not allowed to just fix code and give it back to you. For one that's against the rules, but more importantly you don't learn anything from it
Me who writes the code and give to people: 🤫 Don't tell Robin the truth
so I might be a bit crazy
but
from disnake import Embed
Embed.add_field = Embed.add_field(inline = False)
```this wouldn't work
I thought it would then while writing I realised it wouldn't
I can't change a value without calling the func
Embed.add_field.inline = False
I wanna assign it a False default value
!d disnake.Embed.add_field
add_field(name, value, *, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
cuz it's true
You might be able to subclass it and overwrite it or smth
Tbh I don't know much about subclassing
You here?
yeah
uh...its your wish..really...
Hm?
there must be some indentation issue or else?
Sorry I don't get you
uhh just show then smh
What lol
the imports
imports sir 
import library
import ....
import .......
that screenshot
the place where you're getting the error, not elsewhere
pip install dnspython
in the shell
Alright
subclass Embed?
Yes
Totally not lurking around 👀
@slate swan I got now like something no clue what but, like all my commands work. Just till when I use my warn command I get this error 1m later.
thanku hunter 😔
Share the code
Cool
!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.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Rest of the honors is all yours, I'mma just go play smth
Hm, it was working today though, Any idea how to fix it?
Okay?
👍 Try except exists
i'll just go vomit and brb then
enjoy your game
Thats not how it works. You either share the code or not get help
Lmao don't joke around
I'm not joking 
Nobody is interested in stealing your code
😔
But I am- nvm
@maiden fable Everything works fine, but whenever I use my warn command everything just stops
😔 Okay then, best of luck ig
use motor-
Then show it, ig?
How? I asked it before
Send everything. Something else in the file is wrong
Show what? I get no error at all
Not anymore erm
Why do I get the feeling you're self Botting
When warning I just get no error at all, And then the bot does not respond anymore for 1m
okay then dont ask for help ||dont tell am being rude now||
No clue if you can use this
Nobody is interested in stealing your stinky code
Uh okay
U need dnspython
How?
!pypi dnspython
What is dnspython?
I already got it installed though, how to use it on how to fix my code.
Idk tbh. But pymongo library needs it
u dont use it. U just need it installed
I got it man
But still doesn't work
show me ur code
Of what, the warn command?
Ye
also, is the database url correct?(password etc)
Should be since it worked on my vsc
alr
Just copied my code from vsc to replit and now its not working 
Isn't that fun?
Not really no
It is 🥺
Then just use replit 😄
I am using it
Hehe 
So...?
How to make the bot send a random message
Random module
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
cluster = MongoClient("mylink")
database = cluster["discord"]
collection = database["warn-database"]
class Warn(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(manage_messages=True)
async def warn(self, ctx, user:discord.Member=None, *, reason=None):
id= user.id
if collection.count_documents({"memberid":id}) == 0:
collection.insert_one({"memberid":id,"warns": 0})
if reason==None:
return await ctx.send("Please mention a reason")
elif user==None:
return await ctx.send("Please mention a user!")
warn_count = collection.find_one({"memberid":id})
count = warn_count["warns"]
new_count = count + 1
collection.update_one({"memberid":id},{"$set":{"warns": new_count}})
await ctx.send(f"Warned {user.mention} for **{reason}** in **{ctx.guild}** | They now have **{new_count}** warnings!")
def setup(client):
client.add_cog(Warn(client))
``` Code for my warn command
!d random
Source code: Lib/random.py
This module implements pseudo-random number generators for various distributions.
For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.
On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.
Yeah, but how
Do you want the messages to be in a list
There r two gud ways to do this
idk tbh, i think that u have to fix ur db settings 🤷🏾 (the security system whatever that called)
you are being rude asf
I mean, it worked 2 hours ago and it works on vsc but not on replit

Lmaoo ig mood swings
I send you my code
😔 lets swap
For list:
`
import random
list = [“g”, “y”]
G = random.choice(list)
await ctx.send(G)
#I don’t care about the discord modules and how the await is outta async I’m lazy`
Eh, nah thanks. I also got a cold since the last 2 weeks or smth
Anyone?
Hahahaha my code do be worse than yours
u got logging on?
Replit is bad
i recommend u to use the user id as _id
yeah id is a built in
What logging on?
@slate swan gonna explain u. Me tired
I just use it to work with my dad which is way easier
i just woke up from a 17hour nap
U r up, sooooooo
Also btw databases don’t work on replit
Any way to make ai for discord so my guests can generate their own images for fun? I have the ai models saved in my google drive
Huh, why?
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('~witz'):
numWitz = random.randint(0, len(randomWitze))
await message.channel.send(randomWitze[numWitz])``` It can‘t send the message
That might be my problem then
Replit doesn’t save things about it stops running
lol im still gonna leave cuz arl here
hello, how can i do that the bot set the channel permissions to the user can see them? now its works for the user who click the button.
OOOOO BYEEEEE THEN
@buoyant igloo Do you know if you can host a free bot on vsc
I am also going. @vast gale honor all yours
my nitro had expired yesterday and someone gifted me it again
😔
me too
Idk cuz I never used anything outta replit (I code on mobile)
Mobile ow
anyways I gtg cya later
imagine 
@buoyant igloo
Use random.choice
NO COME BACK U
I try
.
so for disnake, there's an option to install disnake[voice] for "voice support"
ye
but what does "voice support" entail?
idk i never looked into it
connecting to VCs and playing audio and stuff like that
oh to get my bot to actually join a vc
so not things like listening for when users join a vc
Well u can join a VC without the voice one iirc
joining can be done without the voice addon or whatever u call it
You cannot just play audio without the subpackage
gotcha ok
hello, how can i do that the bot set the channel permissions to the user can see them? now its works for the user who click the button.
well you can get your bot to join a vc, it's more about actually playing audio through the bot
w/o voice support it can join but you won't be able to play any audio
I think you need PyNaCl as well
cool cool. that wasn't obvious to me at all
Yup, gonna raise an error
I haven't gotten an error but with logging enabled it does say something like "PyNaCl is not installed, voice is NOT supported"
someone?
Yea, but doesn't it raise an error with that msg? Idk
list= ["file=discord.File('outlaw.jpg')","file=discord.File('outlaw2.jpeg')"] basically i want to add the images without the links to the list which i later call using random but it is not working can anyone help me
how come you have those as strings?
would you not just have a list of discord.File objects?
and then do something like this ```py
await ctx.send(file=random.choice(your_list))
Send a image you want on discord then copy media link put that in the list
i dont want to send the link i have uploaded the image file and want to use it
It won’t
Im making so when a member joins is shows the invite code, ive imported from discord import invite, but im getting the error: and i dont know how to fix it
AttributeError: 'Command' object has no attribute 'code'
@bot.event
async def on_member_join(member):
print(f"Member {member.name}")
print(f"Invite {invite.code}")
print(f"Inviter {invite.inviter}")```
Make sure u copy the media link not message link
@buoyant igloo is it also possible to mention someone in a list? Something like: list=["yes {author.mention}", "no]
you have to put the list in an async function
import discord
import os
from discord.ext import commands
from dotenv import load_dotenv
client = commands.Bot(command_prefix = ".")
load_dotenv()
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs/'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
TOKEN = os.getenv("DISCORD_TOKEN")
client.run(TOKEN)
``` Why doesn't this work?
i dont want to use the image link but the actual image in the list
can anyone help how to do that
there's no env named DISCORD_TOKEN
Erm, how not?
I made a variable for it?
you mean sending a local image?
where's the image?
oh nvm, sarthak god here
daxles, show that variable.. with your token removed
yes but im using replit and ive uploaded the image file there

Thanks
.send(file=discord.File("path to file"))
Can you help me?
i have like 2,3 images and i want to randomize them so i was using a list how do i include them in the list
No I mean the variable that is just in my code if you get me
.send(files=[discord.File("file1"), discord.FIle('file2')])
list= ["outlaw.jpg","outlaw2.jpeg"]
item=random.choice(list)
user_id="545503381700214801"
await ctx.reply(f"<@{user_id}>",item)
this was my command
you need to add the token to the env, you will see a tab named envs in the left bar
Yeah I got a .env file with it in it
why did you do that

await ctx.reply("@buoyant badge",file=discord.File(item))
no spoonfeed
DISCORD_TOKEN=mytoken
Anyone, please?
what does the time argument in Tasks.loop do?
how do i use it?
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
no i dont get how to use that argument what does it do like provide a timestamp abt when the loops gon execute?
import discord
import os
from discord.ext import commands
from dotenv import load_dotenv
client = commands.Bot(command_prefix = ".")
load_dotenv()
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs/'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
TOKEN = os.getenv("DISCORD_TOKEN")
client.run(TOKEN)
``` Anyone, please?
or sumn?
The token is None
Looks like it couldn't find your token
Yeah I get that, how will I fix that?
Make sure your token is set up properly
This is my env: ```py
DISCORD_TOKEN=mytoken
Yeah os.getenv() gets it from your operating system's environment variables
I would love to but I'm not exactly sure on how you would add environment variables on windows
Though I think if you look up "how to add environment variables on windows" there are plenty of articles
??
https://stackoverflow.com/questions/63530888/how-would-i-go-about-creating-an-env-file-for-my-discord-bot-token this site does not say that
No, but os.getenv() gets a value from your environment variable as the name implies
Right now you don't have your token set in your environment variables, hence the error
So I need to do that?
Well that's the whole point of os.getenv()
No clue, that's what the website said.
That would be like do I need to have a json file to use json.load()
So yes, you do
Just putting it out there but it's probably not the best idea to follow random stackoverflow answers with 8 upvotes
imagine the same person asking whats that, F.U.N.
I would not be a happy camper
go to the secrets section of your repl
I am not in repl anymore
Well make sure you have a .env in the root of your directory
oh nvm then
And make sure the syntax is correct
It should be
Its in the same as in the main file
And the main file is in the root of your project directory?
@buoyant igloo do you know how to make a command which tells something from an website like random quotes?
Yes
U want to pull quotes from a website?
Hm, perhaps try a config.json file or something of the sort if .env isn't working out for you
It was an example. I want to pull jokes from an website
Find one that has an API. best to avoid scraping unless necessary
Already found one: witzapi.de (german jokes) but now idk what to do
Does it have an API?
Idk, it‘s called Joke Api when you translate it
I see
So what should I do?
Try to debug .env but if it doesn't work out a config.json file would work
Not the best idea to make a file for each command. This is not discord.js, cogs are for categories not commands.
Just what you prefer?
One of the things I hate about discord.js, yeah
oh
Group related commands into one cog
Alright
For example, moderation commands like warnings, warn, ban, kick, delwarn, can all be grouped into one moderation.py cog
@unkempt canyon's sourcecode is an excellent learning resources to structure your bot
Oh it's open source
https://github.com/python-discord/bot/blob/main/bot/constants.py could be useful in figuring out how to store and load config files
Damn that is cool
Can you help me try and fix it?
Most of our applications are open source
I've never used .env, only json files as javascript and json work very nicely together
That's why I'm saying you could use a .json file for your tokens and other secrets
I can't attest to it's security
So I have a discord bot that stores things in a JSON file. Is it possible that when users spam the command or two users try to use the command at the same time that I the file gets reseted?
And is it possible that a file gets reseted because of 600MB storage left
So how will I do that?
Yes, very possible that the file gets corrupted and you lose all your data
I strongly recommend not using json as a database, rather use a proper database like sqlite or postgres
So you know @buoyant igloo ?
json.load(...) loads a file object as a regular python dictionary
Yeah I just got no idea on how to do that uh
Is there a correct way to make a bot get an invite? I tried this:
invite = await guild.get_invite```
config.json:
{
"bot_token": "some token"
}
import json
with open("config.json", "r") as f:
config = json.load(f)
print(config["bot_token"]) # prints bot token
very simple but works
await guild.invites() returns a list of invites
will that work for getting the specific invite a user joined from?
You'll have to implement that logic yourself, since there's no native way to tell
oh it's that easy
never used json before
How are you saving user warns?
Mongodb
I see, nice
json is decent for startup configs or static content like this
Just still need to fix my warns it now only warns in like all servers. for example I warn someone and I will check in another server it will still do the same if you get me
store guild id too
How will I acces it here? ```py
client.run()
Yeah just need to figure out how ;p
Get the contents of the config file at the top of your file
with open(...) as f:
config = ...
bot = commands.Bot(...)
# commands here
bot.run()
But probably better if you use a subclass
Yeah I have that
And override the default run() method
env files are good for storing tokens...
It wouldn't work
Yes but we were having trouble with them
oh
How do you get the bot token from the json to the client.run?
import discord
import os
from discord.ext import commands
import json
client = commands.Bot(command_prefix = ".")
with open("config.json", "r") as f:
config = json.load(f)
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir('./cogs/'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run()
The bot token would be something like config["bot_token"]
client.run(config["bot_token"])
Do you got expierence with mongodb to maybe help me fix that?
return str(payload.emoji) in ['✅']
payload = await bot.wait_for("raw_reaction_add", check=check)
await payload.member.send("hey")``` this does nothing for some reason
no I don't, maybe you can ask in #databases
Alright thanks
@commands.command()
@commands.has_permissions(administrator=True)
async def suggest_off(self,ctx):
db = sqlite3.connect("Suggest.db")
cursor = db.cursor()
cursor.execute(f"SELECT schannel FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
res = cursor.fetchall()
if not res:
return await ctx.send("На этом сервере и так отключены идеи")
else:
cursor.execute(f"DELETE FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
db.commit()
await ctx.send("Идеи успешно отключены")
def setup(bot):
bot.add_cog(suggest(bot))
wanted to start with a new command suggest but one error came up: discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.suggest' raised an error: TypeError: cogs must derive from Cog sys:1: RuntimeWarning: coroutine 'Command.__call__' was never awaited
And yes I have sqlite3 installed
import discord,sqlite3
from discord.ext import commands
class suggest(commands.Cog):
def __init__(self, bot):
self.bot = bot
print('Module {} is loaded'.format(self.__class__.__name__))
db = sqlite3.connect("Suggest.db")
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS suggestion(
schannel BIGINT,
guildid BIGINT)""")
db.commit()
db.close()
@commands.command()
async def suggest(self,ctx,*,sugest = None):
if sugest == None:
return await ctx.send("Указывайте идею обязательно")
db = sqlite3.connect("Suggest.db")
cursor = db.cursor()
cursor.execute(f"SELECT schannel FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
res = cursor.fetchall()
if not res:
await ctx.send("На этом сервере идеи отключены.\n Включить можно командой `suggest_set`")
else:
for i in cursor.execute(f"SELECT schannel FROM suggestion WHERE guildid='{ctx.message.guild.id}'"):
suggest = i[0]
sug = self.Bot.get_channel(suggest)
emb = discord.Embed(title=f"{ctx.message.author}",description=f"{sugest}",color =0x26bbe0)
mesage = await sug.send(embed = emb)
await mesage.add_reaction(":heavy_check_mark:")
await mesage.add_reaction(":heavy_minus_sign:")
await mesage.add_reaction(":heavy_multiplication_x:")
db.close()
You're aware sqlite3 is blocking?
@commands.command()
@commands.has_permissions(administrator= True)
async def suggest_set(self,ctx,id:int):
db = sqlite3.connect("Suggest.db")
cursor = db.cursor()
cursor.execute(f"SELECT schannel FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
res = cursor.fetchall()
if not res:
cursor.execute(f"INSERT INTO suggestion VALUES('{id}','{ctx.message.guild.id}')")
await ctx.send("Канал для идей успешно установлен")
db.commit()
else:
cursor.execute(f"UPDATE suggestion SET schannel='{id}' WHERE guildid='{ctx.message.guild.id}'")
await ctx.send("Канал идей успешно обновлен")
db.commit()
db.close()
@commands.command()
@commands.has_permissions(administrator=True)
async def suggest_off(self,ctx):
db = sqlite3.connect("Suggest.db")
cursor = db.cursor()
cursor.execute(f"SELECT schannel FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
res = cursor.fetchall()
if not res:
return await ctx.send("На этом сервере и так отключены идеи")
else:
cursor.execute(f"DELETE FROM suggestion WHERE guildid='{ctx.message.guild.id}'")
db.commit()
await ctx.send("Идеи успешно отключены")
def setup(bot):
bot.add_cog(suggest(bot))
Your class name is suggest and so is the function name, it's getting confused on what to add
Classes should always be PascalCased so change your class name to Suggest
thank you!
it can
or CamelCase or UpperWord same thing really
can/has to?
can, you can also do it without parameterized queries but then there's the risk of sql injection
if you're working with user input
I dont really get the docs, but basically, given a message ID, I want to get the amount of ⬆️ reactions and ⬇️ reactions, how can I do this?
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function no-longer raises `InvalidArgument` instead raising [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)").
I get that
its a method of the Message class
i get that, but, i want to see who else reacted
so, given a message and a reaction, I want to know the count
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
lol
thank you very much
np!
i wonder why its not set as a property in docs?
so, just for clarity, the code would look like this?:```python
message = <The message>
reactions = message.reactions
for i in reactions:
if i.emoji == '⬆️':
upvoteCount=i.count
else if i.emoji == '⬇️':
downVoteCount=i.count```
ok, thx!
why not use list comps?
what are they?
generators casted in a list
i still don't quite get it, sorry
!e print([a for a in range(101)])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
i know that
why not use it do you not know the exact syntax?
!e print([a for a in range(101) if a == 21 else print('no')])
hey so im trying to make an avatar command that sends an embed with the image as the persons pfp, but it wont work, theres no error it just doesnt do anything. heres code:
@commands.command(name="avatar", aliases=["av"])
async def avatar(self, ctx: commands.Context, target=Optional):
if target == None:
image = await self.get(ctx.author.avatar_url)
embed = discord.Embed(title=f"{ctx.author.username}'s Avatar:", description="** **")
embed.set_image(url=image)
await ctx.send(embed=embed)
and yes the cog is set up right
So Im trying to do a massban for a list of users
heres my code
@bot.command()
async def massban(ctx, *, users):
await ctx.send("Starting to ban, this might take a while.")
newVar = users
for user in newVar:
banUser = int(user)
print(banUser)
await ctx.guild.ban(user=banUser, reason='Massbanned on {} in UTC Timezone.'.format(datetime.utcnow()))```
and the error is
```py
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
AttributeError: 'int' object has no attribute 'id'```
error handlers? did you load the cog?did you added it and is the command in the class?
target=None, and you should create an else statement
yeah we can't help with that
everything is set up right, the problem is inside the command, before i added the command everything worked perfectly
youll get ratelimited and the code can be used for malicious stuff
oh yea i forgor it has to have admin perms but ratelimited?
how come carl can do it then btw?
@silent ermine why not do it like this
async def massban(ctx, *members: discord.Member):
for member in members:
await member.ban(...)```
everything is not right. if it doesnt work theres something wrong. so please paste your code with the code blocks given by discord
why help with such a command bro?
use greedy?
Greedy is for middle args
oh
its for admin commands o-o
I helped with args parsing
alright ill try that ig
code blocks given by discord?
still youre asking to get ratelimited and can be used in malicious ways.
!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.
it cant be used maliciously if its for admins though
but alright
!paste
what if you ping so much users it goes above ratelimits?
@slate swan https://paste.pythondiscord.com/narekoqiko
you should probably add a has_permissions deco to lock it for admins then only 😔
thats the code in the cog
lmaooo
i have it on now jeez
oh nice
how is it going to ping o-o
just, asyncio.sleep()
you know the member obj takes ids and mentions right?
in your for loop or whatever
no.
and usernames
thats what is is, not asyncio.wait, i havent used that in so long i forgot what it was
yup
what is discord.User.colour and discord.User.accent_colour?
Sus thing I haven't heard about
using sleep isnt a good option at all
i see lmao
!d discord.User.colour
property colour```
A property that returns a colour denoting the rendered colour for the user. This always returns [`Colour.default()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour.default "discord.Colour.default").
There is an alias for this named [`color`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.color "discord.User.color").
What the heck
i want more info than that
What kind of color does it access fr
dumb docs
One sec ima check dev portal
the apis ratelimits are dynamic for http requests so you would get ratelimited yes it will work for the default limit
I'm guessing the prominent one in their avatar, like how they do it with the default banner
this is apparently it
well thats just a comment
i got my friend to join for that (using on_member_join) and i got what i just sent. this is their profile
it would be None because nothing was given
yeah, their's should be orange
light mode be like
@undone tartan turns out this is somehow related to banner
you mean the banner color?
your's will 90% be yellow, I'm guessing | try it
oh
@slate swan heres code you wanted
does it mean this thing?
yeah see, the default one!
ah
that's the one rendered by discord by default
discord.User.color will return the default one
but how would it be an integer representation of a hexadecimal colour code
if it just returns the default one, whats the point lmao
no sorry, i meant the profile colour
why the heck do you have to initiates and why is there a default value of optional?
default just seems to be #000000
youre supposed to add the base hex code
wdym
if its 000000 in py it would be 0x000000
0x iirc means the base of hex codes which are ints
i mean it returned as a string
no.
well that would send a string but the base is an int
hm ok
0x000000 is an int lol
but it still doesnt explain why it gave 000000 when the banner clearly isnt black
thats the default value of it right?
no clue
well check source code in dpy and check its default return value its probably 000000
initiates?
i followed a tutorial i was given
yes you have 2 dunders
.
im so confused
well you didnt followed it right to have 2 dunders
well the default is probably what i said
alr
musta been that, yeah i should seen that
so itll always be the default?
yeah
i dont understand why that is a thing but alr
you have members intents i suppose yes as your member join got triggered
kinda makes sense ig
guys
yeah i have that intent on
?
did you check src on how all the methods work?
please ive been sobbing for the past 5 minutes now pycontainer@pterodactyl~ Server marked as running... Traceback (most recent call last): File "/home/container/peperun.py", line 34, in <module> client.run(TOKEN) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 723, in run return future.result() File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 702, in runner await self.start(*args, **kwargs) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 665, in start await self.login(*args, bot=bot) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'
no cos it sounds confusing
wrong token
but
regenerate your token and add it again
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
change it
heh
okay i reset it
doesnt discord reset it itself tho
no.
No
or how does that work now since they changed it
only if you pushed on github
I’ve accidentally pushed my token to GitHub 🗿
So do I just insert the new one in
TOKEN = os.getenv('tokenid')
since discord and github have a system that searches tokens
same here
no in the variable
on the value of the var
went to check the "leaked token" message and i saw like 100 of these and they are only in this server, a bit weird imo
lol
How to make tables in postgresql? (heroku and git)
you can make database tables in PgAdmin
i..
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import *
from discord.ext.commands import has_permissions, CheckFailure, check
from dotenv import load_dotenv
load_dotenv('---.env')
TOKEN = os.getenv('OTA3MjMyMTI4NjE2NTEzNTU2.**')
print("hi")
client = discord.Client()
client = commands.Bot(command_prefix = '!')
@client.event
async def on_ready():
print("this bitch is in")
@client.command()
async def ping(ctx):
await ctx.send("Pong!")
client.run(TOKEN)``` where would that be located
Or through queries
that is not how dotenv works-
fuck
Why do you have a client and bot initialized
hold on what the heck?
its os.getenv('NAME_OF_THING_IN_ENV_FILE')
@slim ibex isnt this sus?
for example:
in dotenv file
TOKEN=HDJKFHKSEGskseahgv.srghshgsbsBYgwEV
in bot
os.getenv('TOKEN')
yes
no idea
let me ping mods and talk to them about it
There is actually a discord announcements thing
do you use replit?
but that many?
But idk if it has an ID or multiple IDs
in .env
DISCORD_TOKEN={stuff}
i mean you can look for yourself
How to do it on git? Or just make a table in code?
I think it’s just an admin thing
but theres so many tho it looks like a botnet
yeah that can work
no pterodactyl
git has nothing to do with Postgres
CTRL+K and then @discord
git is a version control system, Postgres is a database
Learn SQL before using databases. Then you can checkout ORMs, and other database stuff
prolly a botnet
yeah, considering the pfp is not even transparent with the dark mode colour
ok, so then make a new file and call it .env, the in it put the following:
TOKEN=#your token here
then put this at the bottom of your main file:
bot.run(os.getenv("TOKEN"))
The discord announcements one has the discord logo
yeah but theyre users
the announcements one is @Discord#0000
no reptile. sed
bot = discord.Client()```?
client?
oh
bro?
ive never done it that way before
why use the Client class
ive only ever done bot = commands.Bot(...) lmao but thats just me
That’s what you should do
because the Bot class is the subclass of the Client class
oh yeah client.run(os.getenv("TOKEN"))
ah
(subclassing it is best)
!d discord.ext.commands.Bot you guys ever read docs?
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
sorry, bot is way less confusing to use so i use it instead but you use client so use that
should be able to if you have members intent
Heeelp Stackoverflow is down
no clue, id love to know too
not sure what it would be called tbh
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.
it might not
does it not have access lmao
https://discord.com/developers/docs/resources/user looking at this, its not mentioned
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hm but ive seen so many people with their name as everyone
does the api just not have a bot endpoint thingy for bios
Traceback (most recent call last):
File "/home/container/peperun.py", line 24, in <module>
bot.run(os.getenv("TOKEN"))
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'```
your token is wrong.
a friend tried to help me
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext import *
from discord.ext.commands import has_permissions, CheckFailure, check
from dotenv import load_dotenv
load_dotenv('---.env')
print("hi")
bot = commands.Bot(command_prefix = '!')
@bot.event
async def on_ready():
print("this bitch is in")
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
bot.run(os.getenv("TOKEN"))```
ok
load_dotenv doesnt have anything in it
its just load_dotenv()
ok uhm
regarding the token, i've just reset it yet the error is pretty much the same py Traceback (most recent call last): File "/home/container/peperun.py", line 24, in <module> bot.run(os.getenv("TOKEN")) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 723, in run return future.result() File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 702, in runner await self.start(*args, **kwargs) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 665, in start await self.login(*args, bot=bot) File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip' are there any other reasons for that
try without dotenv for a sec
It isn’t a string
just put your token as a string as a test
that’s why it’s raising
are you using replit
strip() is a string method
if it werent a string it would raise an attr error
hold on remove it from requirements.txt or just remove load_dotenv()?
remove os.getenv bit
k
since the token is wrong it would be None and the method cant parse None only strigs
@slate swan
no pterodactyl
Traceback (most recent call last):
File "/home/container/peperun.py", line 23, in <module>
bot.run(os.getenv("TOKEN"))
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 723, in run
return future.result()
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'```
dont call me that. and why are you using an env just set your token directly if youre using an editor.
no i mean, i'm using pterodactyl
im so confused at this point
what even is that
an editor? or an online editor?
my friend just checked, bio's just arent a thing on the api
its a docker server appliance
he knows what hes doing considering he wrote a library so i feel like he would know lmao
I think it's a hosting platform
this is so weird
iirc bots cant access bios did he check the apis endpoints?
never heard of it tbh
I have
i think he just checked the user object to see
it was cheap
i mean aint it a bit overkill for something you arent sure works fully yet
you can run it on your own computer for free
One should always dockerize applications when deploying to production
it is 💀 i use that docker for mc servers tho
when doing that yeah, but it wasnt even working for them until a second ago so like
imagine refering your bot as a she
shoo
mhm uhh
i dont even refer my bots as any gender i refer to them as an obj
My last off-topic message for today: It cannot be non-binary, can it?
its not even alive.
That was a joke
ik
is it just me who finds it kind of weird that you can get someones email from the discord api?
like it feels kinda icky
you can?
i doubt that
discords security smh
just open the browser client and check the payloads lol
why does discord even return the id as a str
too long? wait no that doesnt make sense
i forget how, but im sure theres a way to instaantly register a slash command (using discord-py-slash-command)
it should be an int or atleast set 2 different versions
other than kicking and reinviting the bot
just use 2.0 it has slash commands
discord-py-slash-commands turned into interactions.py which joined p*cord
I think because the length is always between 18 and 21
21?
why would that matter?
I.. do not know
000000000000000000000
thats so long
My own user ID is 350619697231691776
urs is 18
i doubt the length matters
the problem isnt the library tho, its the registration of the command
That's what she said
it was done by setting a server id instead of letting it do it globally
ive used it before, and i remeber doing something to make it instant
your mom told you that?
at the start of every slash command decorator youd put it in there
yeah! does it still work?
yeah!
It was yet another joke
geez, a lot has happened in a year
its not released yet
clone the repo
i wanna use smth stable
disnake
hm?
!pypi disnake
i mean novus is also a fork of discord.py
never heard of it
I have never heard of it either
they didnt change the favicon to not discord.py lmao
can anybody send me the src code of how dpy connects to websockets and how the bot acknowledges hb?
maintained by voxel fox
its not very big but its useful
has support for everything atm
seems like a cheap copy of dpy
ok but it works so like
like pycord copies everything and renames everything
pycord is amazing !
doesnt even rename dirs
sure it is, you should check source code
yeah! love the owner too :)
it won't show if hes not in the guild
it showed tho
.bm | thanks mark!
lol
it sends a dm to you lol
you making a discord wrapper?
ah lmao
no i just want to learn how to handle websockets so i can wrap an api with websockets.Why you want to make fun of me like always go ahead couldnt really care.
im not making fun of you 
figured them both out
bios are on the api but return empty string
colours and accent colours are weird just ignore them
other guilds say something else about you. oh sorry i shouldnt say this so you can get the helper role oops
silly me
whats going on lmao
hmm maybe i should make fun of you 🤪
sure. You look like a clown tho you cant even contribute to projects because you lack skill.
xD
@manic wing can i just say ur pfp doesnt look cool, just makes you look like an edgy 14 year old who drinks monster in their room alone watching tiktok cos they have nothing to do
lmaooo
with that im not going off topic anymore
same here
@slate swan how do i use your discordheximals thing?
it looks cool and the default colours are boring
just pip install it and import it i should release a new version with good name spaces
yeah maybe ill work on it to make it better and i couldve made it better with dynamic attrs but it is what it is lol
!pypi discordheximals
returns hexcode by name for discord.py and its forks
just pip install it and import it
ill fix when i get home for sure
alr
and im going to rename the package aswell
so maybe dont use it until tomorrow or later on today
too late lmao
then upgrade it later on today
is there anything about it that is specific to discord?
i mean its just hex codes under names lmao
vscode isbeing a bitch and wont import it
yeah which couldve been methods bound to an instance and properties as well or even better couldve been done with an iteration of a list and setting attrs dynamically
reportMissingImports my balls
its just the package's initiate file
ok
thats why i said to install it later
its horribly done
sure
!warn 729135459405529118 quite unnecessary. read our #code-of-conduct and #rules for the expectations we have for community members.
:incoming_envelope: :ok_hand: applied warning to @undone tartan.
?
i think its to do with something from another server
and they mayve felt attacked from the other guys comment?
because you can do <@>
oh
@manic wing i do remember a couple times you went out of your way to critique some people's projects in a less than constructive way, but didn't have a chance to say anything.. if it's becoming a habit pls keep that in check.
i would like to clarify, i didnt do a single thing?
just something from memory, it was quite a ways back and in an off-topic channel
what comment?
okimii always feels attacked
Hey i just have a question rq, im at a friends pc rn, were trying to make a bot but we get that no file or directionary error, even tho our file is in the same folder as the python file...
noted
Fix what
would you be able to take a screenshot?
^
yeeaaaaa lemme make his discord acc join here one sec
ello
heres that screenshot
ohhhh its running in the random stuff folder
alright I see whats going in
only on interactions
wait how do i make it run inside the folder inside random stuff folder 💀 i feel dum rn
I would get set the path to be "Python/token.txt"
or just use a period lol
ah oke
but the period sometimes gives an error unlike the way he suggested
how can i just like run it inside the python folder
so its just C:\Users\Lukas\Desktop\random stuff\Python
I'm unsure about doing it through vscode specifically but if you run cd Python in the terminal and try it again it may work
works 👍
is there some way to use member.add_roles() to add more than one role at a time? If I use a list it gives AttributeError: 'list' object has no attribute 'id'
just iterate through the list
ok
what theme is that
solarized dark
cheers
Take deep breaths, maybe you’re so stressed that it isn’t working that you’re shaking
hello guys how can i grab my emoji to this code c emoji="\U0001f468\u200D\U0001f3eb
or how to use custom emoji
You can use * in front of the list
anybody?
lol
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 531, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot_base.py", line 610, in on_message
await self.process_commands(message)
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot_base.py", line 607, in process_commands
await self.invoke(ctx)
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 912, in invoke
await self.prepare(ctx)
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 833, in prepare
if not await self.can_run(ctx):
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 1159, in can_run
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 567, in async_all
for elem in gen:
File "C:\Users\Saad\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 1159, in <genexpr>
return await disnake.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "c:\Users\Saad\Desktop\Files\test\mymindisdead.py", line 30, in __call__
raise commands.CommandOnCooldown(bucket, retry_after)
TypeError: CommandOnCooldown.__init__() missing 1 required positional argument: 'type'```
any idea?
bucket is the type 
Hello!
on dpy 2.0 its CommandOnCooldown(cooldown, retry_after, type) since the Cooldown object was refactored to not have a bucket type associated with it
im using a custom cooldown
alr alr
quick question, so the cooldown is the current cooldown?
the cooldown object thats being applied
Hey so I am trying to get premium and normal commands for my bot anybody has ideas
basically what get_bucket() returns
tnx alot
you should have a database that stores whether a given user has premium, and a custom command check to handle allowing your premium users
how would i use if certain element is 0
oh wait I dont have a website or dashboard the premium is a role in the code that says when a user has this role in my server they should access some premium commands
oh, then you can just use the builtin @commands.has_role(<role id>) check then
iunno think of stuff that matters most to your server
wdym and requests isnt async
!pypi aiohttp
ok
https://www.tiktok.com/legal/terms-of-service
automated access of tiktok is against their ToS
then fix it
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I did but it's not working
async def on_member_join(member):
wEmbed = discord.Embed(title="test",description=f"{member} test :white_check_mark:",color=0x55cc55)
await client.get_channel(834899978131472429).send(embed=wEmbed)```
error?
there isn't a error
caeden it had .send method lol
i wasnt paying attention
happens
let me see your bot constructor
the whole code?
the bot constructor.
if "element" in i: else statment wont work
dumb question but how? idk what you mean
?
what constructs the bot
the "bot variable"
like client = command.Bot
oh
Bot, it should be bot
i got client = discord.Client()
That's better
but idk if this would solve my problem
Do you have an error handler?
No
@sick birch may I ask what the difference between commands.Bot and discord.Client is?
commands.Bot has support for message commands, event listeners, and cogs/extensions
ide = str(r.content)
for i in ide.split(','):
if "element" in i:
await ctx.send("element found")
else:
await ctx.send("element not found")
await bot.process_commands(ctx)``` how to fix else statment wont work
ignore syntax
Could u send Full code
sure
I'd like to see the params and the variable named 'element'
@bot.command()
async def checker(ctx, *, element):
r = requests.get("website")
#print(r.content)
ide = str(r.content)
for i in ide.split(','):
if "element" in i:
await ctx.send("found")
else:
await ctx.send("not found")
await bot.process_commands(ctx)```
requests 😢
yes
ps content is already str
wym
that was print for test
o u mean ide variable
Anyway, not the problem
the problem is else statment doesnt work
thats why i added end
await bot.process_commands(ctx)
@manic wing when element doenst exist it still sends found
added what?
.

lol
@manic wing summary: if element doesnt exist it still says it does due to if statment not working
Where do u define element
Oh nvm
lol
Its not a variable
no its part of command
Can u show me the print?
wym
The output of the print r.content
why are you processing a command
and its not even indented properly
it spam replys
ik
its a for loop
Send me the output please, it can help
the process part no
Remove it, it's only for on_message events
its a for loop it will iterate through all the elements you need to break the loop
kk
!d break
7.9. The break statement
break_stmt ::= "break"
``` [`break`](https://docs.python.org/3/reference/simple_stmts.html#break) may only occur syntactically nested in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) or [`while`](https://docs.python.org/3/reference/compound_stmts.html#while) loop, but not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional `else` clause if the loop has one.
If a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) loop is terminated by [`break`](https://docs.python.org/3/reference/simple_stmts.html#break), the loop control target keeps its current value...
@slate swan please send me the output
the output is found 2x
break just sends element 2x
Try printing r.content and send me that output
ok
are you running 2 instances ?
@bot.command()
async def checker(ctx, *, element):
r = requests.get("website")
#print(r.content)
ide = str(r.content)
for i in ide.split(','):
if "element" in i:
await ctx.send("found")
else:
await ctx.send("not found")
break
?
God
wait
That's not an instance
i forgot to change break
ok sorry
I already found the reason it isn't working
U got a param element in ur command, u check for the word 'element' and not for the param. 'Element' will always be returned, str(element) not
the element always comes back poositve(if) even though element is negative(else)
Yeah I literally just explained that
ok
U are checking for the word element
yes
Not for the element parameter
are else statments even possible on requests
Remove the " " from element and ur issue is fixed
ok
⁉️
How come he doesn't get that he checks for the word element and not his parameter element
lmao
trying to make a ticket dropdown command
error is discord has no attribute to Select
That's literally his only issue
yes
Are you on dpy 2.0?
@slate swan is it fixed?
appreciate the f-strings
how do i check i forgot
and you define a class every time the command's called??
commands.Bot is a subclass of discord.Client, which mean it's a superset. commands.Bot has all the features of discord.Client, and more such as command handling, cooldowns, converters, etc
So what's the point of using discord.Client?
no point
incase you don't wanna use commands
?
so you don't want to waste memory for it either
A bot without commands
Nothing really
If you're just doing a quick testing project with no commands or anything it it I guess you could use discord.Client
dont use commands. continues to do if message.content.startswith()
not your type of chat either #esoteric-python



