#discord-bots
1 messages · Page 481 of 1
I only use GitHub to transfer my code to the Raspberry
you can get it
I want to make a discord bot,
when a user joins the server it adds points/score in inviter's wallet
Does anybody know how to handle events uniquely. So think of a cog. But then it’s like 1 cog instance per discord user. Is that possible??
How can I make a presence to my bot like this?
anyone has the idea of how to rig my gamble command?
?d discord.on_member_join
How?
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None, afk=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
I mean, my school doesn't have an email system
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/stable/api.html#discord.Game "discord.Game")
• [`Streaming`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Streaming "discord.Streaming")
why
Bots don't support those images and stuff
you dont need a school mail, you just need to prove that you are a student
ah
h o w
Have a verifiable school-issued email address or upload documents that prove your current student status.
didnt read it carefully
Hmm, so ID Proof?
yeah
Ah ok
Anyone?
hey rush, you have the idea on how i would rig my gamble command? i have no idea rn
it took about 1+ months for my request to get approved
what does a gamble command do?
uh, maybe flipping coins or higher lower numbers?
i think
ill have 2 commands to gamble
maybe i should uh
sad
I know how to do
the problem is with Database
you can use the random module
yeah but if they get too much the economy will get inflated lol
so im trying to rig it a lil bit
i just dont have the idea
maybe compare the last time to current time that theyre gambling
and decrease their luck
yaeh yeah thats nice
why wont the custom emoji work?
embed = discord.Embed(colour=discord.Color.from_rgb(244, 182, 89))
embed.add_field(name=f"{member.display_name}'s balance", value=f"""Bank: **{user_account[1]}**
Wallet: **{user_account[2]} <:turtoge_coin:id>**
Items: {user_account[3]}""")
embed.set_footer(text=f"Requested by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)```
maybe give it a very high cooldown
@lament mesa i got the idea of the gamble command rig now >:)
just check if the last time they gambled was near
then just decrease their luck
is that a good one rush
yeah but it can be used a lot of times
yeah but decreasing their luck must make them stop
ngl should we add foods to our bot
and make users lifes difficult
lmao this sounds uh
idk
maybe?
anyone know why is the custom emoji not working?
bc the id must be an actual id??
ye i know
i cant put the actual id
why not
🤨
cuz if i put it only shows :turtoge_coin:
hmm
is the bot in the server where the emoji that you're trynna use is in
yes
then what's "not working"
it doesnt show the emoji
what does it show then
:turtoge_coin:
try bot.get_emoji(id)
see if that return None
it return none
done that already
then the bot isn't in the guild
ITS IN THE GUILD
xd
then it shouldn't return None 🤨
do u have intents
yes
hey kraots
should i rig my bots gamble command?
idk, u do u
Are you sure you copied the ID correctly 🤔
^
yes
Just send the emoji with a \ before it
wdym by that?
Wdym how does it work 🙂 you just saw how it works
like how does 1632299274 relate to 3 days
3 days doesnt seem to be 1632299274 milliseconds..
I think that's unix timestamp
i already had discord installed and i am using repl.it it worked before but idk what happened now it aint working and saying this all the time
You can search it up
oh ok, thanks
replit bad
it worked perfect before lmaooo
We working with time?
maybe a problem with the lib or replit it self
Why we working with time?
hmm
it was working fine until i decided to add a queue using asynchio
What are you trying to do? Have you considered using sqlite3 to create a database and use a background task (loop)?
umm no i have no idea what that means lol, should i send my code ?
Maybe. describe what you want to do?
play music, but it was working all good until like a few days before it says discord module couldnt be found
@client.event
async def on_member_join(member):
inviter = await tracker.fetch_inviter(member)
channel = client.get_channel(872704194337980547)
cursor = await client.db.cursor()
await channel.send(f"{member} joined! Invited by {inviter}")
await cursor.execute("INSERT INTO money (guild_id, inviter_id, money) VALUES (?,?,?)", (member.guild.id, inviter.id, 10))
await client.db.commit()
await cursor.close()
this giving me error
your insert command is wrong.
await cursor.execute("INSERT INTO money VALUES(?,?,?)", (member.guild.id, inviter.id, 10))
oh thanks
why removed those values?
idk why you're inserting tho
you're adding a new entry. you've already created the table so all you're doing is adding a new row
but how do I update it?
can I come in DMs?
with update instead of insert
@mortal thistle you ever done the PDO method in PHP to update a database?
This is similar
i still manage to get it wrong but it's still similar
You have duplicate data in the table
but the column has a unique constraint
pip install discord.py
i did
incorrect
wdym env
oops i meant install
How do I get the exact number of messages in a channel?
Can you do pip freeze in your console?
in terminal?
yes
last_message = await channel.history(limit=1).flatten()
thanks
`python -m pip freeze
What’s pip freeze?
It shows all installed packages and versions
And dpy isn’t in there, so you need to install it
Pycharm makes its own venv for every project automatically
So doing it in your command prompt or terminal won’t work
Because venv
doesnt seem like he has separate venv
Is there anyway, to fix replit operation failed? Over 24 hours now 😥
Pycharm ALWAYS makes a venv for every project by default
Not use replit :p
🤣
What replit operation failed? wym
Package operation failed
Error?
Replit is supposed to be an online IDE and such but like I hate it in every aspect
shouldn't there be like pycharmprojects\xyzproject\main.py
Also if you’re making a discord bot it means you are quite proficient with python, why are you using an online IDE that is super feature limited? @crystal cliff
Why not just a good ide like pycharm or VSC or atom or whatever
pycharm is very laggy for me vsc not so much
Cause pycharm & vsc don’t work on my laptop. No comp 😥
Buy remote desktop protocol
What’s that?
I have actually never heard anyone come with this kind of issue…? How old must your laptop be to not even be able to run VSC?
No idea, how to do that lol
2weeks old lol
notepad++ can also be used
Then surely it can run VSC
you can use literally anything
Or notepad for that matter
it doesn't really matter
???
If you use a cell phone use a replit application or a glitch
I’ve had no trouble, with replit until now 😥
How does an IDE not work for you lol
Prob be fixed, by tomorrow, (crossed everything) 🤣
I'm using my mum's old laptop and she bought this 6-8 years ago and it only has 2GB Ram and I'm able to run VSC rather smoothly
I’m not familiar with vsc, will prob, download it later.🤔
Help me please, I'm trying t o use cogs but it fails everytime i run it
Exception has occurred: ExtensionFailed
Extension 'cogs.fun' raised an error: TypeError: __init_subclass__() takes no keyword arguments
File "C:\Users\WINDOWS\Desktop\DISCORD BOT SPIDERMAN\cogs\fun.py", line 5, in <module>
class Fun(commands.Cog, description="Furry"):
The above exception was the direct cause of the following exception:
File "C:\Users\WINDOWS\Desktop\DISCORD BOT SPIDERMAN\main.py", line 31, in <module>
client.load_extension(f"cogs.{file[:-3]}")
/// ERROR
if __name__ == '__main__':
for file in os.listdir("cogs"):
if file.endswith(".py") and not file.startswith("_"):
client.load_extension(f"cogs.{file[:-3]}")
/// code
VSCode works on my 8 year old laptop, so it can work on any laptop in existence
Remove the description= kwarg
Not sure who told you, but you cannot have a description= in a class like how you did
wait
class Fun(commands.Cog, description="Want to have fun? Look at these pages. So cool."):
def __init__(self, client):
self.client = client
this is from my main bot lmao
and even if i dont put the description, it wouldn't work still
what is the full error
client.load_extension(f"cogs.{file[:-3]}")
Please provide a full traceback to your exception in order for us to identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / 0
ZeroDivisionError: integer division or modulo by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (e.g. ZeroDivisionError)
• Make note of the line number, and navigate there in your program.
• Try to understand why the error occurred.
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
yeah ik i screenshotted it wait
Extension 'cogs.fun' raised an error: TypeError: __init_subclass__() takes no keyword arguments
File "C:\Users\WINDOWS\Desktop\DISCORD BOT SPIDERMAN\cogs\fun.py", line 5, in <module>
class Fun(commands.Cog, description="Furry"):
The above exception was the direct cause of the following exception:
File "C:\Users\WINDOWS\Desktop\DISCORD BOT SPIDERMAN\main.py", line 30, in <module>
client.load_extension(f"cogs.{file[:-3]}")
this is full error
thats it?
yes
send your cog's full code
import discord
from discord.ext import commands
from PIL import Image, ImageFont, ImageDraw
class Fun(commands.Cog, description="Furry"):
def __init__(self, client):
self.client = client
@commands.command(pass_context=True)
async def info(self, ctx):
img = Image.open("images/white.png") #Replace infoimgimg.png with your background image.
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("fonts/TextFont2.ttf", 15) #Make sure you insert a valid font from your folder.
server = ctx.message.guild.name
role_count = len(ctx.guild.roles)
member_count = len([m for m in ctx.guild.members if not m.bot])
draw.text((0, 0), server, (0, 0, 0), font=font)
draw.text((0, 25), f"Verification Level: {ctx.guild.verification_level}", (0, 0, 0), font=font)
draw.text((0, 50), f"Highest Role: {ctx.guild.roles[-1]}", (0, 0, 0), font=font)
draw.text((0, 75), f"Number of Roles: {str(role_count)}", (0, 0, 0), font=font)
draw.text((0, 100), f"Number of Member: {str(member_count)}", (0, 0, 0), font=font)
img.save("images/infoimg2.png")
await ctx.send(file = discord.File("images/infoimg2.png"))
def setup(client):
client.add_cog(Fun(client))
the error still happens even if you remove the description=?
uhh the error is gone but when i try executing the command from that cog, it doesnt respond.
you indents are kinda fucked up there
Cos the commands not in the cog. Indent it
oh fuck yeah
remove pass context
not needed after 1.0
how?!?!?!
pip install discord.py
BRUH I ALREADY DID THAT
and?
do it again
Well not in your venv because it’s not in the pip freeze
i did it
in the venv
Do pip freeze again and see if it shows up
And that’s one of the major reasons I stopped using pycharm
It’s just so many things that make it more annoying than helpful
atom seems better but im in linux
idk
anyways im changing to windows in 2 - 5 days
so it doesnt matter i will save the code in a usb stick
yeah it was fucked this whole time man, was stuck here for 1 hour but i instead waatching movie lmao
btw the reason why i said 2 - 5 days wich is long because i have a problem and might change the whole disk
is there a http interaction bot library in python
As in sending data over the internet?
Also kinda wrong channel since this is for discord bots
yeah im talking abt bots lmao
discord slash commands can be made over http
http interaction bots
i think they're asking about that
dpy doesnt offer anything to do with slash commands
first search result gave me this https://github.com/LiBa001/discord-interactions.py
has a flask extension
oh alr thanks
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
I’m not the biggest expert but sounds like a fun project, could you maybe send me some more info?
Ofc
DMs?
In this case sure, normally I would say no but this is something else haha
I need help,
members = ctx.author.voice.voicestate.channel.members``` how do I get this to work?
I am trying to get all members inside the authors vc
First get the author's VC
Then use discord.VoiceChannel.members method
!d discord.VoiceChannel.members
members```
Returns all members that are currently inside this voice channel.
why does it pick the debug file rather than the file that's just downloaded??
import os
file = os.listdir("/sdcard/! workspace/annoy/")
print(file)
im making a discord.py bot where it downloads a video and converts it into a MP3 (on user's command)
I can do all that but the file that was downloaded, couldn't be picked by os.listdir???
<VoiceState self_mute=False self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=633907166851366928 name='general' rtc_region=None position=1 bitrate=64000 user_limit=0 category_id=633907166851366927>>```
how do i convert days in years, months?
anyone? ^
please ping when reply
Can methods of one Cog call the methods of another Cog?
Divide by 365
Then the remainder to 12
You could also use a package like datettime
No
You can only call commands from another cog
Not sure why not
can u give an example?
But I think just put the methods on a new file and call it from that file
year = day / 365
month = (day % 365) / 12
It's weird, but it's true sadly
There is no way to import the methods from one cog class? That's disappointing
how to convert datetime obj in days?
wdym?
a cog has a method and you want to use it?
you can use Bot.get_cog
can then use whatever method you want
I'm trying to make a embed like this: ```py
embed = (discord.Embed(title='Now playing'.format(self),
why isn't Now playing a hyperlink ?
you cant have hyperlinks like that inside a title
there is the url kwarg though
change a person's name im guessing
like the command thats in the python bot
i mean cant you just google a list of names
why isnt the activity working?
class Zion(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or('z.','Z.'),
intents=discord.Intents.all(),
case_insensitive=True,
activity=discord.Activity(type=discord.ActivityType.watching, name=statuses)
)
i need watching status, not playing
oh
how can i convert datetime.datetime obj to days?
x = datetime.datetime.utcnow()
accountAge = x - user.created_at```
sorry xd
how to make like the discord.py bot send messages to all channels like an important announcement?
all channels of one server?
yes
i need it for like a BIG announcements
datetime has a days attribute
anyone please? ^
for channels in ctx.guild.text_channels:
await channels.send('msg')
why
he gets what he wanted
yeah
oh
no?
no?
accountAge = (x - user.created_at).days() like that?
maybe that
read the tos
can u take a ss
me?
yeah
what's the thing to get a member's permission in a specified channel
where it says that
just .days , take this as an example
user.permissions_in()
https://discordpy.readthedocs.io/en/latest/api.html#discord.User.permissions_in
perm = dict(ctx.channel.permissions_for(ctx.author))
await ctx.send(perm)
why it send both of the beg1 and beg2?
beg1 = await economy.add_money(ctx.message.author.id, "wallet", random_amount), await ctx.send(f"An old lady gave you **{random_amount}**, because you begged her so much.")
beg2 = "Get a job kiddo, stop beggin! - Rich guy"
beg_list = [
beg1,
beg2
]
await ctx.send(random.choice(beg_list))```
because you're doing await ctx.send
and beg1 is going to be a tuple
cuz you're doing beg1 = func1(), func2()
ohhhhhh, tysm for helping
asked this half an hour ago, still anyone?
not dpy related
is the file you wanted not in the list?
or discord bot related even
it is, the .MP4 file
blanket is cool. yeah it's not discord
even though that application is discord, it's still not that
os.listdir will pick all the files/folders in the directory , use endswith func to filter the file you need
how do I do that? I don't use os... so I have no idea
import os
file = os.listdir("/sdcard/! workspace/annoy/")
print([x for x in file if x.endswith('mp4')][0])
```maybe?
does anyone know how i could have two multiple word arguments because it only allows one *
async def vote(ctx, *title_input, *options):
!e py example_dir = ["video.mp4" , "afile.py"] for file in example_dir: if file.endswith(".mp4"): print(file)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
video.mp4
take this as an example
oh
thanks
I have been head scratching a lot since yesterday... lol
async def vote(ctx, title_input: str, options: str): @simple kettle
x = datetime.datetime.utcnow()
accountAge = (x - user.created_at).days
years = accountAge/365
months = (accountAge%365)/12
accAge = f"{years} years, {months} months"```
@slate swan
how do i avoid decimals?
:.0f
in years
or wrap it in round()
use round function , os just use int(years)
best one :3
yeah int() should do the job but just use 2 decimals rather than removing all
am stupid
me more
why is the months coming as 12.5?
magic
because you're dividing it with 12
just round it too lol
did not work the way i wanted to, i want to make the command like this .vote Should we play games or code code,games
ohh that's gonna be hard. knowing when to stop accepting args
try accepting just one string file and then split with ,
use a single string and ask the users to provide a sperator
yeah thats what im about to do
I heard discord.py get shutdown
it didn't. more like discontinued
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_option
client= commands.Bot(command_prefix=">")
slash =SlashCommand(client, sync_commands=True)
token = ''
@slash.slash(description='SETUP UR ANTIPRUNE')
async def AntiPruneSetup(ctx:SlashContext):
if ctx.author.id == ctx.guild.owner.id:
embed = discord.Embed(color=0)
embed.set_footer(text='Development')
embed.set_author(name='Project', icon_url='')
embed.set_thumbnail(url='')
embed.add_field(name = "SettingUp", value = 'Anti Prune is Setting up')
await ctx.send(embed=embed)
role = await ctx.guild.create_role(name = 'Anti prune')
for mem in ctx.guild.members:
try:
await mem.add_roles(role)
except:
passcl
embed = discord.Embed(color=0)
embed.set_author(name='Project', icon_url='')
embed.set_thumbnail(url='')
embed.set_footer(text ='Development')
embed.add_field(name = "Finished", value = '✅ Finished up setting AntiPrune')
await ctx.channel.send(embed=embed)
else:
embed = discord.Embed(color=0, description=f'**`Only {ctx.guild.owner} Can Run This Command!`**')
embed.set_footer(text='Development')
embed.set_author(name='Project', icon_url='')
embed.set_thumbnail(url='')
await ctx.send(embed=embed)
client.run(token)
Whats the error
its just no longer being developed officialy , there are forks continued
how do i convert the remainder of years into months?
is there a traceback?
use on_command_error and Bot.get_channel
!e
x = 12.7
print(f'{x//1} {(x-(x//1))*12//1}')
@lusty swallow :white_check_mark: Your eval job has completed with return code 0.
12.0 8.0
Then what happend if discord.py is no longer being developed?
It won't get updated and eventually will be outdated.
It might even get deprecated and not work anymore if Discord decides to change their endpoints.
But we still able use discord.py right?
ask in #python-discussion ig
Thanks
If Discord changes their endpoints, no.
https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1 it wont be developed anylonger
Oh okay, thanks for the info🙏
did you add a listener for interaction
Wait i am sharing replit multiplier link in your dm you can see
dont pls
Shit
!ytdl
Does anyone know how to make your bot react to its own embed?
msg = await ctx.send(embed=embed)
await msg.add_reaction("emoji")```
!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/stable/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/stable/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/stable/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
I hope you not playing growtopia private server or developing that
x = datetime.datetime.utcnow()
accountAge = (x - user.created_at).days
years = accountAge//365```
accountAge gives me 1610days , which is equal to 4.4109... years. how can i convert the remainder/decimal value `.4109` in months?
with math
You can probably string format the time instead to make things easier but idk how to do it
uhhh... ummm.......
i have a channel dedicated to gtps server 😂
anyone know why im getting emoji unknown error
msg.add_reaction(":one:")
how to fix this?
beg1 = (await economy.add_money(ctx.message.author.id, "wallet", random_amount), f"An old lady gave you **{random_amount}**, because you begged her so much.")```
Is there any way to call the methods of a cog outside of the Cog?
Like how you could import the methods of a class, it seems like it works differently with cogs hence why I am asking
i already told you to use Bot.get_cog
you are sending a tuple
Is this a response to my message?
i dont know, you tell me
I see, I scrolled up. I didn't see that you had responded. I will go read the documentation on the method you proposed
help pls
Hi, is there an event that can "intercept" when bot messages are sent. e.g. if a message contains a bad word, it prevents from sending it and that for every commands
anyone know why im getting emoji unknown error
msg.add_reaction(":one:")
you must precise emoji's ID. If it's a default emoji, put \1️⃣ instead of :one:
uh
you need to get the emoji ID not command
how do i get the ID
Is it a custom emoji or default one?
I think in dev mode you can right click and get the id that way, there are likely other ways as well
no this one 1️⃣
it's a default one so you can use on your keyboard Windows + dot and then search for the one keycap
should look like that in your IDE
thank you it worked
no. It's on_message to get a sent message. or look into wait_for
thanks
What is this?
why does the bot output two errors
That is not a class instance that you are calling add_reaction on
Visual Studio Code
that was just to show an example
I mean you did it on a class and not instance
I know, it was an example...
how to make a cooldown to minutes(mins), hours(hr), day(d), and week(w)
I had a similar error before. Maybe because the file runs twice, i restarted my computer and all was fine
guilds```
The guilds that the connected client is a member of.
Where does Process come from?
args is not defined why?
it is outside of the function
yea but if i put it inside then the if statement doesnt work
Multiple instances
you're not missing a colon?
you're missing a colon and the line is not inside of the function. args is local to the function
lmao looks like someone doesn't like kiwi
what is the error
indendation
send the traceback
intendation*
lw = str.lower
This is incorrect
.lower() is a method so you need the brackets
and str needs to be an actual string instance
I think he got a indent error from the text editor
is there a way to change the speed of something that is playing in discord.Guild.voice_client
Try rewrite that
Try re write the code inside food commands
i mean i have tried it a bunch of times
lw = str.low is not a line you should dentate
>>> a = str.lower
>>> a("AbOR")
'abor'```
you solved my problem tysm i alsmost spent 2 hours in this shit
hey guys
🤔
()
yes but str needs to be an actual string instance
okay
@Bot.command()
async def food(ctx, args):
apple = "Yumm tasty"
banana = "ahh relaxed"
kiwi = "Eww get his out of here"
lw = str.lower
if lw(args) == "apple":
await ctx.send(apple)```
Try paste this
What's the point of putting str.lower inside a variable if you're not going to use it?
str is not even defined
I edited
mhm
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
do you know what indentation is?
I don't want to be that guy but if you seriously spent 2 hours on an if statement indentation you should learn the basics again
bru
you got a github page? kinda curious on what's your approach
I swear one problem goes then another arises
I'd suggest tabs
pep8 says to use spaces, and tabs only to maintain code that already uses tabs
It's a a little on an early phase since we're not forking it
The github page is empty but I'm discussing the features with the other devs of the project in a server
I get that this seems like nothing, but trust me, I plan to actually do it
@client.command()
async def check(ctx, arg):
if isinstance(ctx.channel, discord.channel.DMChannel):
await ctx.send(arg)
``` what does this snippet do? I understand that the channel is being compared to a DM, but how can I modify it to return a boolean value?
isinstance returns a bool
Well, thats what isinstance does. It returns wether or not the object passed in as the first argument is an instance of the second
does the arg parameter mean anything if I only need the isinstance value?
discord.channel.DMChannel
sounds kinda like a non-existing thing
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
`x == y` Checks if two channels are equal.
`x != y` Checks if two channels are not equal.
`hash(x)` Returns the channel’s hash.
`str(x)` Returns a string representation of the channel
it does exist
thats a module
bru
DMChannel gets imported in the __init__.py file
you can either do discord.DMChannel or discord.channel.DMChannel
nice
if you want to check whether it’s a DM you can also check if ctx.guild is None
I got this in a file.
How can I do to adapt these 3 lines, for a x number of tokens I have in a database ?```py
Token1 = ""
Token2 = ""
Token3 = ""
bot1 = commands.Bot(something)
bot2 = commands.Bot(something)
bot3 = commands.Bot(something)
loop = asyncio.get_event_loop()
loop.create_task(bot2.start(Token2))
loop.create_task(bot3.start(Token3))
bot1.run(Token1)
You can use a for loop
a for loop
To iterate through the list of tokens
and create_task as you used
Just a question, why do you have a list of tokens?
but I can't create variables in a for loop
you can?
Of course you can
And add them to the list
But again, why do you have a list of several tokens?
here i cant use blank variable?
because it will be for users. And they will have a "custom" bot made by me, for them
how ?
Oh I see
list_of_bots = []
for token in list_of_tokens :
list_of_bots += discord.Bot(things)
https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji.is_usable
Whether the bot can use this emoji.
does it refer to all bots?
is there any alternative way for this?
all bots?
does it?
what do you mean all bots?
Well currently if you don't pass anything and just do !test it'll error because it expects something in args
Add a default value to args
example?
async def test(ctx , args = "") :
if args is None
Won't work currently
why?
Because you would try to see if args is None, but it'll never be None if you set the default value to ""
Yeah ofc he has to set it to None by default
Unless you set it to None which is totally ok, both "" and None will work perfectly
but i want to add some more if blocks to !test which will accpet args
accept*
i only want args to be none temporarily
not for the whole command
Have some trouble with this await channel.edit(name=cname)... The trouble is when i doing it several times
I have no idea what it is
You're probably getting rate limited
what is that?
Does anyone know how i could get all the reaction that were used on this message
and can i do something about it
You have to do it every 10 minutes
Discord blocking you if you try to do changes like that several times in a short time
Or you'll be blocked from doing it by the API
how many changes can i do every 10 min?
One edit call and as much as changes as that edit call can get
can u edit several channels in on call?
I believe so
No
Not serveral channels with one edit method
Channel1.edit
Channel2.edit
thats old code
ok thks
etc
It's probably really old
Oof
It's guild, not server
so you tried something knowing that it is outdated?
I'm not sure why the command is not registered, but I know that it still won't work
@bot.command()
Ah yes 
ye okay thanks
Either set the default value to None as well or change what you're comparing to to ""
but how do i set the default value
the args = "" is settings a default value, you can do args = None
can anyone help me
@plucky shoal
i want to set different role perms for different channels
like the verify channel must have send messages perms
Can anyone help me with an issue i am having with put my bot on a hosting service?
but the rest of the channels should not have them
how do i get like this?
https://media.discordapp.net/attachments/381963689470984203/889173879573078026/unknown.png
i want to set different role perms for different channels
like the verify channel must have send messages perms
for this
@lament mesa
message.guild.channels is a list, you cant await it
Make a requirements.txt for your project using pip, then push the code
pip freeze > requirements.txt
```Your hosting service needs this to know what packages to install, as showing in the startup command
i did but it sent like <name:id> thing
yeah, cause its a code block
i dont want the thing with id
what should i change it to?
how to send a message from the objects returned from a function?
want do you want it to be, because list's aren't awaitable
await Messageable.send(func())
i want like
Huh? That works?
then await send("`:ping:`")
oh ok
from discord.ext import commands
bot = commands.Bot(command_prefix="!",case_insensitive=True)
@bot.command()
async def setverifychannel(ctx,channel : discord.TextChannel,member = discord.Member):
if channel == channel and ctx.message.author.guild_permissions.manage_permissions:
await channel.send("TYPE !verify in my dm to VERIFY")
guild = ctx.guild
UnverifiedRole = discord.utils.get(guild.roles, name="unverified")
if not UnverifiedRole:
UnverifiedRole = await guild.create_role(name="unverified")
for channel in guild.channels:
await ctx.channel.set_permissions(ctx.guild.channel, send_messages=False)
else:
await ctx.send("You dont have admin perms or you haven't give the correct channel name")``` i updated it
yea
but this is not working
error?
channel == channel will always return True
``` now?
now?
whats should i write in the requirements.txt import discord?
No, you should use the command I provided to put your project's dependencies into it
It's why it's suggested to use a venv
does that panel have a startup tab?
Do you want to check if it's a text channel?
yes
if isinstance(channel, discord.TextChannel)
thank you
@slate swan could i pm you?
yeah
Yo @lament mesa
Oops you are offline. Sorry
Anyways lemme post the issue and the code
guys
?
who have a code academy account dudes
I'm pretty sure it should have a history method
Tho you should check the docs
# read background image only once
#url = ''
response = urllib.request.urlopen('https://cdn.discordapp.com/attachments/766262034459131914/854713117417144320/unknown.png')
background_image = Image.open(response) # it doesn't need `io.Bytes` because it `response` has method `read()`
background_image = background_image.convert('RGBA') # add channel ALPHA to draw transparent rectangle
```Imma tryin to get this urllib to open `https://cdn.discordapp.com/attachments/766262034459131914/854713117417144320/unknown.png` but i get the errors like this
Forbidden just means you aren’t allowed to do that
You’re not allowed to view it for instance
soo i aint allowed to view wt i can....welp thn wut else can i do?
You’re not allowed to do this action
Check what line exactly the error is coming from btw
Maybe it’s another line
makes sense...i mean i had gotten this code frm stackoverflow....and it had a image url...and it works only for that
https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png?download this is the url which was there
welp any idea how to get it to work?
That too
edit the code n gib plis...wud really appreciate tht
We don’t spoon feed code
i dont spoonfeed
Use an image which isn’t forbidden to view
You just don’t have access to the image that’s all
i mean iz in a priv channel but the bot do have access to it...does tht matter or smtn else?
but, you first instantiate an aiohttp.ClientSession then using that client session you send a GET request to that url using aiohttp.ClientSession.get or request and passing in the method as GET and the from there use await ClientResponse.read, it gets returned by the method mentioned, read returns bytes
aighty i shall try dat
Well because you’re making a new session with a different library it will see it as any random internet stranger and not as the bot
mhmm
You would need to authorize yourself completely and go through that entire process to be able to view it as the bot
oki
actually it shouldnt return forbidden
you're able to view images without any authorization
how do I loop the presence
no it isnt
As in?
async def on_ready(self):
self.change_presence.start()
@tasks.loop(seconds=300)
async def change_presence():
servers = len(client.guilds)
members = 0
for guild in client.guilds:
members += guild.member_count - 1
await client.change_presence(activity = discord.Activity(type = discord.ActivityType.watching,name = f'{members} members'))```
Is this correct?
300 seconds is way to short for the rate limit
It’s like twice per 10 minutes iirc
what
So you need to wait 5 minutes
thats for channels
@lobby1.command()
async def result( ctx, *, result):
db = sqlite3.connect('my_database.db')
cursor = db.cursor()
result = str(result)
#TEAM CHANNELS
lobby1_team_a = bot.get_channel(870969338901954606).members
lobby1_team_b = bot.get_channel(870969338901954607).members
lobby1_team_a_id = []
for member in lobby1_team_a:
lobby1_team_a_id.append(member.id)
lobby1_team_b_id = []
for member in lobby1_team_b:
lobby1_team_b_id.append(member.id)
if result == 'team a':
for user_id in lobby1_team_a_id:
cursor.execute(
"UPDATE main SET user_elo = user_elo + (?) WHERE user_id = (?)",
(elo_win, user_id))
user_ign = get_user_ign(user_id)
user_elo = get_user_elo(user_id)
await member.edit(nick=f'[{user_elo}] ' + user_ign)
for user_id in lobby1_team_b_id:
cursor.execute(
"UPDATE main SET user_elo = user_elo + (?) WHERE user_id = (?)",
(elo_lose, user_id))
user_ign = get_user_ign(user_id)
user_elo = get_user_elo(user_id)
await member.edit(nick=f'[{user_elo}] ' + user_ign)
when i do the command =lobby1 result team a, it doesnt actually change anything in the database. can someone explain to me why?
what should it be?
do you know when we should use self
{'embed': <disnake.embeds.Embed object at 0x0000028D751D75E0>, 'ephemeral': True}
This is the dict, how to make it so that the embed and the ephemeral are passed into the send_message() method?
Sorry I dont
async with session.get(url, headers=headers, params=querystring) as response:```this works?
send_message(**mapping)
ah ok thanks!
if you defined session, url, headers and querystring yeah
but i am guessing you copied it from somewhere
prev command tht i had yes
because sending a simple GET request doesn't require extra headers and params
this fine?
yes, but you should instantiate a single global session
like this
bot = # bot definition here
async def create_session():
bot.session = aiohttp.ClientSession()
bot.loop.run_until_complete(create_session())
aiohttp starts crying if a session is created outside an async function
this near bot.run?
before it
use something that you have inside your head to think about why that happened
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
welp...peace
@hasty iron how dont you have the helpers role you've helped almost everybody
no not really
Cap.
You deserve it tbh
agreed
In the same line you're encountering the error
ok just do Image.open(await response.read())
And that's why you deserve the helpers role
oki
...
help
can you print response.status
one sec
you arent commiting
(i think)
dint print jackshit but this came up
i hate myself (i think).. im gonna check on it tmrw cuz its 2.am for me
lmao
hadnt.....now i did
hm
whats the full traceback for this
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 1996, in canvas
background_image = Image.open(await response.read()) # it doesn't need `io.Bytes` because it `response` has method `read()`
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/Image.py", line 2912, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: embedded null byte```
ok try this
data = await response.read()
background_image = Image.open(io.BytesIO(data))
np
Blanket is from the best and nicest people I've seen in the community.
i dont think im really that nice, sometimes people here get on my nerves
That doesn't make you not nice, some people deserve to be gone rage on.
You still help them, which makes you nice.
well thanks i guess
g! embed
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
No problem.
but make it async obv
why a class
just make a utils file
and import the function from there
how i can do custom color in the embed?
pass in the color kwarg
are you worried about scopes?
yea
scopes is my bot.
!scope
Scoping Rules
A scope defines the visibility of a name within a block, where a block is a piece of python code executed as a unit. For simplicity, this would be a module, a function body, and a class definition. A name refers to text bound to an object.
For more information about names, see !tags names
A module is the source code file itself, and encompasses all blocks defined within it. Therefore if a variable is defined at the module level (top-level code block), it is a global variable and can be accessed anywhere in the module as long as the block in which it's referenced is executed after it was defined.
Alternatively if a variable is defined within a function block for example, it is a local variable. It is not accessible at the module level, as that would be outside its scope. This is the purpose of the return statement, as it hands an object back to the scope of its caller. Conversely if a function was defined inside the previously mentioned block, it would have access to that variable, because it is within the first function's scope.
>>> def outer():
... foo = 'bar' # local variable to outer
... def inner():
... print(foo) # has access to foo from scope of outer
... return inner # brings inner to scope of caller
...
>>> inner = outer() # get inner function
>>> inner() # prints variable foo without issue
bar
Official Documentation
1. Program structure, name binding and resolution
2. global statement
3. nonlocal statement
import it
@potent jetty import platform
basically rather than doing
embed1 = ...
async def whatever():
...
you'll do
class Foo:
def __init__(self):
self.embed1 = ...
async def whatever(self):
...
blanket already said that but ok
i think both are fine
but personally ill go with the first one
i dont see a need for a class here
yeah
and await it ofc
editing channel overwrites
uh wait
!pypi mcstatus
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
look into the overwrites kwarg
I used it to make this bot, pretty sure it's the same result you want.
if ctx is a Context object yes
why are you going to use the channel id
channel can be a TextChannel object
so just call edit on it, with the params you want
How could I present aliases to certain commands?
@bot.command(aliases=['alias1', 'alias2', 'etc'])
pass in aliases into bot.command
it takes in an iterable
no
embed field values or the other thing cant be empty
comma for multiple aliases?
thats just a list
Or it just won't recognize it all?
k thanks
you could just pass in the whole message object and inside the function do message.channel
yea
yea..vscode does that sometimes
..maybe put in your own token
I have.
client.run('token')
Tried that.
try this
yea..remove os.getenv()
you did not enter the token in your env tab
Could you show your line 18?
^^
enter key as TOKEN and value as token there
How come this isn't working?
inviter = await tracker.fetch_inviter(member)
It returns none type?
.env
I'll try that.
load.getenv()
Token = os.dotenv(DISCORD_TOKEN)
bot.run(Token)```
Or whatever variable you use to store the Token
Doesnt work.
What's the variable that youre using on your .env file?
could you please show your file view ( list of files in your project)
since replit does not allow .env files
they have their own environment variable tab instead
are you using replit ?
Which IDE are you even using?
Yes sir.
it does
The video allowed it.
it does?
if you use an .env file
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
Got it off there.
NOOOOOOOOOOO
weird, thought they didn't allow it
oh god..don't. It's great for learning..but not for hosting your bot 24/7...your bot will get ratelimited all the time
Oh alright.
NOT THE FREECODECAMP TUTORIAL MAN
if you want i free host i cand send you the one i use..works preety well
it probably doesn’t work pretty well
i mean..i have 600 mb ram and a full core for free..good for hosting a text bot
it has cons
your bot can get ratelimited easily , your project is public ..
u talking about repl.it ?
yes
How do I get my bot online?
i will send you the host i'm using in a dm. is that ok ?
Yes.
Hey I created a welcome command on discord.py but I want to make the bot responsd the user welcome when the bot has a role (welcome) how can I code this any help? Python
btw..you will have to code on your machine and upload your files, it doesn't have a online ide like replit
!d discord.Member.roles , you can check if the bot has the role using if role in <botuser>.roles:
roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
or if its a command use a check
Like I have coded this one but still the bot send message when a person joines the server
Code-
commands.bot_has_role("welcome")
it is @bot_has_role("welcome")
yes it should work
But still it is sendin message
is that a event?
I will try
or a command
@slate swan @client.command
it should be @commands.bot_has_role() tho
its a decorator
Okay I will try tomorrow
Thanks for help
I will reply tomorrow that it works or not
ive never tried this deco actually, is the parameter int or str for passing the role?
it allows both
nice.
mhm
thanks
Is there an easier way to get your bot online?
]e ping
You can only use this command in the following channel(s): #878695047112040448, #878694844212592670, #878694948810137621, #878694991784972309, #476196062214750219, #310-release-stream, #bot-commands
how do I make a custom exception
that sends something to a channel
how do I pass the ctx variable to it
meh, not even necessary
You can only use this command in the following channel(s): #878695047112040448, #878694844212592670, #878694948810137621, #878694991784972309, #476196062214750219, #310-release-stream, #bot-commands
If any one have knowledge in discord buttons can u help me out plss
I have created a calculator using discord buttons but when I click on a button it says this interactiion is failed
Can anyone help?
@patent lark @slate swan @slate swan can u help me?
unfortunately, i only have the most simple knowledge about discord.ext.buttons, i havent really got into learning it. sorry.
i think there is a lib called dislash or dyslash
@bot.event
async def on_member_join(member):
inviter = await tracker.fetch_inviter(member)
channel = bot.get_channel(794837147068792865)
await channel.send("Someone has joined!")
print(f'Inviter: {inviter}')
print("--")
```Why won't wthis work?
!pypi dislash.py
discord.ext.commands.errors.NoEntryPointError: Extension 'Cogs.DevCmds' has no 'setup' function.
Shows up on the terminal, athough I do have a setup function
Any help?
Hmm what does it mean?
you need to write the setup function in the cog
It is
def setup(bot):
bot.add_cog(ClassName(bot))```
anybody?
I did ident it
Slash commands?
@lofty mulch
I did place the class name, still shows up
make sure its indented correctly.
