#discord-bots
1 messages · Page 530 of 1
Read it please
ok
he said should i use youtube_Dl ? he didnt say he was gonna use it
the answer is no
yes
:/

Why do you think YouTube shuts down music bots
Might want to reconsider if you really want to make a music bot
from system files?
Then don't make a music bot
ok :((((((((((
then make it
import discord
from discord.ext import commands
class Dm(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def dm(ctx):
await ctx.send("**DM me with your question to create a ticket!**")
def setup(client):
client.add_cog(Dm(client))
How doesn't this work?
This is an event?
just remove the event and replace it with commands.command()
import discord
from discord.ext import commands
class Dm(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.command()
async def dm(ctx):
await ctx.send("**DM me with your question to create a ticket!**")
def setup(client):
client.add_cog(Dm(client))
``` Not like this right
no
oh..
remove everything after the @ and replace it with commands.command()
Okay
Also I got like a big problem with my modmail system, literally every message that I send in my server creates a modmail, it only needs to be when I dm my bot with a question which it does.
import discord
from discord.ext import commands
from datetime import datetime
class Member(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.client.user:
return
else:
guild = self.client.get_guild(867086205182017536)
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name = str(message.author.id))
if channel is None:
category = discord.utils.get(guild.categories, name = "Tickets")
channel = await guild.create_text_channel((message.author.name),category = category)
await message.author.send("Modmail has been created succesfully")
em = discord.Embed(
title = f"{message.author.name}#{message.author.discriminator} created a modmail",
description = {message.content},
timestamp = datetime.utcnow(),
color = discord.Color.dark_blue()
)
await channel.send(embed = em)
else:
em = discord.Embed(
title = f"{message.author.name}#{message.author.discriminator}",
description = {message.content},
timestamp = datetime.utcnow(),
color = discord.Color.dark_blue()
)
await channel.send(embed = em)
def setup(client):
client.add_cog(Member(client))
Don't check every message then
How?
use py if not isinstance( message.channel , discord.DMChannel): return
Check if the channel is a private message channel
Yeah like that
So many spaces 
It's clean though
Where should I put that?
in your on_message event , ad the top
bruh
*at
btw why do u have an else statement
Do you even know how the library or Python works
if channel is None why are you trying to send an embed to it

lmao
Why are you guys just trying to make fun of me
have you coded this by yourself
we're not we're pointing out things
yes... how otherwise would there be mistakes in there
well what is wrong with this? py if channel is None: em = ... await channel.send(embed = em)
we arent we're just criticizing it
Yeah I see that it's not needed
.
But implemented it in a wrong way
Just change it and check if the channel is a DMChannel
Since that's what you want to do
Yeah
Get help from this to check if it's a DMChanel
That works, but my respond system and close system doesn't work as well
Yeah that works
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
if ".close" in message.content:
pass
else:
if str(message.channel.type) == "private":
return
else:
if message.author == self.client.user:
return
else:
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = {message.content},
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete
def setup(client):
client.add_cog(Mod(client))
channels = await guild.fetch_channels()
channel = discord.utils.get(channels, name = str(message.author.id))```
can be changed to ```py
channel = discord.utils.get(guild.channels, name=str(message.author.id))```
and user = await message.guild.fetch_member(int(message.channel.name)) can be changed to user = message.guild.get_member(int(message.channel.name))
Then it says message is not defined
oh i was talking about the on_message, if you mean for the command use ctx instead of message
ah
ctx.guild.get_member
Yeah
But you got any idea how to fix it that it sends the response in dms back and closes the ticket on .close which it doesn't
what do you mean? all the messages you send are to the user
When I am in the channel that has been created by the bot, when I should say for example: "test" it should send that back in dms to the person
which it doesn't
could you show your updated code please
sure
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
if ".close" in message.content:
pass
else:
if str(message.channel.type) == "private":
return
else:
if message.author == self.client.user:
return
else:
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = {message.content},
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete
def setup(client):
client.add_cog(Mod(client))
{message.content} can just be message.content
Yeah I just noticed that as well
thats not the problem though
No I know
maybe remove the try and except and see if anything gets raised
i can't see anything wrong with it
Yeah
apart from you shouldn't be fetching the members unless you really have to
you should be using guild.get_member
which isn't a coroutine btw
Okay
Also
Taking in consideration you previously created channels based on the username and not the ID
Nevermind
What about it?
I can't read
lol
What is your current edited code
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
if ".close" in message.content:
pass
else:
if str(message.channel.type) == "private":
return
else:
if message.author == self.client.user:
return
else:
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete
def setup(client):
client.add_cog(Mod(client))
``` this atm
fix for?
Now what doens't work
Sending the embed back to the user in dms once I send the message in the created channel
u cant send the dm to the member?
When I type a message in the the channel nothing happens
Do you have errors?
Nope
Also, you shouldn't always use fetch_member
Use get_member and then fetch_member if it returned None
what did u type in the channel?
Example here
Just test
what did u expect for the bot to send?
And
await ctx.channel.delete
should be changed to
await ctx.channel.delete()
because it's a method and not an attribute
A embed back to the user in dms with the message test
!d discord.TextChannel.type
property type: discord.enums.ChannelType```
The channel’s Discord type.
hm
You should check if the channel is an instance of DMChannel
How?
Have you tried adding random print statements to see how your code flows
Nope I'll do that now
Yeah you should
Done
It prints 1 1 1 then it prints 5
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
print(1)
if ".close" in message.content:
pass
print(2)
else:
if str(message.channel.type) == "private":
return
print(3)
else:
if message.author == self.client.user:
return
print(4)
else:
print(5)
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
print(6)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete()
print(7)
def setup(client):
client.add_cog(Mod(client))
hm
any clue
import requests
import discord
from discord.ext import commands
import config
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot connected")
@bot.command()
async def join(ctx):
"""target_application_id
Youtube Together - 755600276941176913
Betrayal.io - 773336526917861400
Fishington.io - 814288819477020702
Poker Night - 755827207812677713
Chess - 832012774040141894
"""
data = {
"max_age": 86400,
"max_uses": 1,
"target_application_id": 755600276941176913, # YouTube Together
"target_type": 2,
"temporary": False,
"validate": None
}
headers = {
"Authorization": "Bot token",
"Content-Type": "application/json"
}
if ctx.author.voice is not None:
if ctx.author.voice.channel is not None:
channel = ctx.author.voice.channel.id
else:
await ctx.send("Зайдите в канал")
else:
await ctx.send("Зайдите в канал")
response = requests.post(f"https://discord.com/api/v8/channels/{channel}/invites", data=json.dumps(data), headers=headers)
link = json.loads(response.content)
await ctx.send(f"https://discord.com/invite/{link['code']}")
bot.run(config.TOKEN)```
Hi, I'm new to Python and started learning a few weeks ago. I'm trying to create a very simple discord bot with just one command as of now. And I'm having trouble making the env file for the token. It's responding with this.
AttributeError: 'NoneType' object has no attribute 'strip'
Does anyone know what I can do to fix this? I can even send my code or whatever here.
Learn python first, then learn discord.py
im need help
Lmao bruh I know I'm doing that as well but my friends have actually dared me to make a simple bot thats why im tryin it out but alr
Can you send your code?
i created a bot using python
nice
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
Make sure to use ```py
is your Authorization really "Bot token" or you passed an actual token?
Do you have a .env?
yes
is bot token
await message.channel.send("ldkjfkl") in last line
yes
Yep I'm pretty sure I do.
What do you got in your env?
TOKEN = (the bot token)
should be without spaces
alr lemme try
Are you sure the v8 of the API supports watch together?
You should try with v9 aka the latest
Nope still the same error
share the full code with code formatting
!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.
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
@reef shell
Still, try with v9 you never know
Indentation is wrong
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Done, still the same error.
Well
Can you send your env file with like black your token
That's not how to load env files
it does support
sure
@fathom hamlet take this ```import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=".")
@bot.event
async def on_ready():
print("Bot connected")
@bot.command()
async def hello(ctx):
await ctx.send("hello")
bot.run("token")```
Can you import discord.ext
I'm pretty sure os.getenv works for system environment variables, and not .env files
bruh?
Isn't the fix just to import disocrd.ext
same
ig
sorry
yeah i use dotenv
@junior verge
Yep
Is it like an extension or sum?
My code still does not work to send the embed back in dms
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
print(1)
if ".close" in message.content:
pass
print(2)
else:
if str(message.channel.type) == "private":
return
print(3)
else:
if message.author == self.client.user:
return
print(4)
else:
print(5)
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
print(6)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete()
print(7)
def setup(client):
client.add_cog(Mod(client))
what's wrong?
uh just use a command? @wooden frigate
oh shit
srry didnt want to ping
nah i did that cause i like pings
instead of client.event?
alr lemme try
look:
now it's saying
AttributeError: 'Client' object has no attribute 'command'
@wooden frigate
async def hello(ctx):
await ctx.send("hello")
from discord import commands
Output:
hello
Error: commands does not have Client
Did you mean command.Bot()
does not have attribute Client. You dummy interpreter
Sorry:
I simplify errors
oki
hey, is any of you familiar with Pterodactyl? having a bit of an issue
wanna pull from a private repo, but the current setup requires a bot start file (like src/main.py) which is gonna be available after pulling
and I feel like the pull is not taking place
not sure though
hm
I am not rlly sure if its releated with #discord-bots but ig i need some photos to understand
maybe this will help you out
If not then contact me in DM's i guess so we will not break any convo
Then what should I do now?
^^ thats true i think
@fathom hamlet
Depending on how pterodactyl does it you can still pull a private repo, but it will prompt for your github username and your access token
If it requires you to first have a file you can just quickly write a temp file which uses subprocess open I'd assume to run the command
!d subprocess.Popen
class subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, ...)```
Execute a child program in a new process. On POSIX, the class uses [`os.execvpe()`](https://docs.python.org/3/library/os.html#os.execvpe "os.execvpe")-like behavior to execute the child program. On Windows, the class uses the Windows `CreateProcess()` function. The arguments to [`Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen "subprocess.Popen") are as follows.
*args* should be a sequence of program arguments or else a single string or [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). By default, the program to execute is the first item in *args* if *args* is a sequence. If *args* is a string, the interpretation is platform-dependent and described below. See the *shell* and *executable* arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass *args* as a sequence.
how to add roles to a member
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
*roles???
those are args
ooo
i mean u gotta define what role is first
*roles means you can pass a list however many discord.Role instances you want
ooooh
Sorry I mean't you can pass however many roles you want
Not in a list *
However if you want to bulk add roles it would be better to do Member.edit
await add_roles(discord.roles.id=RoleID, reason=None, atomic=True)```
ohk
Hello friends ,
I'm trying to build a bot that plays music in the voice chat for some friends. I followed a tutorial and fell into some issues with FFmpeg. I have added it to my path so that windows can now access it and convert the audio , but I don't
hear anything from the bot in chat even though its icon is glowing to show its playing. Any help or ideas mates?
.add_roles is an attribute of discord.Member so actually add member and define it
maybe its your volume
hm
yeah it wants the username and the access token, but yeah the issue was that it was trying to run the bot first, and even if it did, I'm not really sure it was pulling it
but thanks for your suggestion :)
If it prompted for your username and access token then it is pulling
i mean i have fields for that in the startup section
I want to learn an easy web scraping tutorial, where can I learn it so that I can send the data through my discord bot
Not really a discord bot related task.
@client.command()
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio('WOW Anime.mp3')
player = voice.play(source)
else:
await ctx.send(f"{ctx.author.mention}, **You aren't in a voice channel!**")
Why it doesn't play the audio? NO errors..
I suggest not copying code off of the internet.
And if you do filter from newest to oldest not from oldest to newest.
cause it says status is None
Nowhere in the docs you can find 'pass_context = True' since this has been depricated since 2017
I removed it and it doesn't work again... @cloud dawn
Returns the primary activity the user is currently doing. Could be None if no activity is being done.
What about now???
it was none for me
i tried it
!d discord.VoiceChannel.connect @shut axle
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
@stark bobcat does ur bot have member intents?
it cant access the members status without them lol
How do I combine this with the code?
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/master/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised.
I mean, what should I change here?
No one?
Throw even more docs lol, fact is that voiceclient is not the nicest class
True
My code still does not work to send the embed back in dms
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
print(1)
if ".close" in message.content:
pass
print(2)
else:
if str(message.channel.type) == "private":
return
print(3)
else:
if message.author == self.client.user:
return
print(4)
else:
print(5)
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = "Message from the staff team",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
print(6)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team")
await ctx.channel.delete()
print(7)
def setup(client):
client.add_cog(Mod(client))```
Weird, that should have worked tbh
Yeah
I suggest getting to know python a bit more before moving to music.
Me?
Does your question relate to audio?
Well other than the fact that it's an on_message command bot. Provide some more info, what print does it stop at, errors, intents etc
When I am trying to send the message back to the user in dms in the created channel from the ticket, it just doesn't do anything
Well that is true because you are getting a user with the channel name? user = await message.guild.fetch_member(int(message.channel.name))
Why are you getting the member if you can just do message.author.send()
How would I write that?
Also this should give an base 10 error convert str to int.
i enabled it
it works now
Nice

Nevermind
Set the user variable to message.author
I fixed it already
Yeah that's the only error I get at the moment
Would've been nice to include also i pointed out what the issue is.
if str(message.channel.type) == "private":
Here?
Change str to int
@cloud dawn Also, what is the name for the person that sends the .close command?
type is a string
yeah
Look here -> #discord-bots message
Okay
Is it ctx.author?
I fixed it already that is fine
I am just asking what the name would be of the person that sends the response
Then it should be fine right
Would that be ctx.author?
This looks like a one way conversation with the bot.
I am trying to get here the name of the person that responded in the ticket
Forgot to add f before the ""
Yeah I did
I get a error if I define ctx
@tasks.loop(seconds=5)
async def my_brain_outdated():
await bot.change_presence(activity=discord.Game(name="Join de group!"))
await asyncio.sleep(5)
await bot.change_presence(activity=discord.Game(name="!help voor de commands!"))
await asyncio.sleep(5)
await bot.change_presence(activity=discord.Game(name="Colza Productions"))
```
NoneType has no attribute change presence,
A friend of me said the bot Is not defined. But It Is.
@slate swan When I send the 2nd message back to the bot in dms it writes the message in {''} why is that?
Again, what's your code
import discord
from discord.ext import commands
from datetime import datetime
class Mod(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
try:
print(1)
if ".close" in message.content:
pass
print(2)
else:
if str(message.channel.type) == "private":
return
print(3)
else:
if message.author == self.client.user:
return
print(4)
else:
print(5)
user = await message.guild.fetch_member(int(message.channel.name))
emb = discord.Embed(
title = f"{message.author}'s response!",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.green()
)
await user.send(embed = emb)
print(6)
except Exception as e:
print(e)
pass
@commands.command()
async def close(self, ctx):
user = await ctx.guild.fetch_member(int(ctx.channel.name))
await user.send("The modmail has been closed by the staff team!")
await ctx.channel.delete()
print(7)
def setup(client):
client.add_cog(Mod(client))
Not this one
import discord
from discord.ext import commands
from datetime import datetime
class Member(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.client.user:
return
if not isinstance( message.channel , discord.DMChannel):
return
else:
guild = self.client.get_guild(867086205182017536)
channel = discord.utils.get(guild.channels, name=str(message.author.id))
if channel is None:
category = discord.utils.get(guild.categories, name = "Tickets")
channel = await guild.create_text_channel((message.author.id),category = category)
await message.author.send("Modmail has been created succesfully")
em = discord.Embed(
title = f"{message.author.name}#{message.author.discriminator} created a modmail",
description = message.content,
timestamp = datetime.utcnow(),
color = discord.Color.dark_blue()
)
await channel.send(embed = em)
await channel.send("<@&868232863592620072>")
else:
em = discord.Embed(
title = f"{message.author.name}#{message.author.discriminator}",
description = {message.content},
timestamp = datetime.utcnow(),
color = discord.Color.dark_blue()
)
await channel.send(embed = em)
def setup(client):
client.add_cog(Member(client))
yep
sorry :/
No problem :P
how can i get a count of all the commands i have in my bot?
What's wrong here
what is the difference between bot.commands and bot.all_commands?
why double fstring?
title = f"{message.author.name}#{message.author.discriminator} - f"<@{message.author.id}>" created a modmail",
and u havent closed the 1st fstring
How do I?
nvm
@waxen granite How would I fix this ```py
title = f"{message.author.name}#{message.author.discriminator}" - f"<@{message.author.id}>" created a modmail",
title = f"{message.author.name}#{message.author.discriminator} - <@{message.author.id}> created a modmail"
.mention
?
I mean.
description = message.content - <@{message.author.id}>,
``` Like how do I do both in the description
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
make it only one
for the 2nd one?
You don't need to always add the f when you want to put a variable in it
Just once in the front and then you can use {} for any variable
See this
ah
@junior vergelearn from this
description = f"{message.content}" f"<@{message.author.id}>",
Without the f
its same
Yes
import discord
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.Listener()
@commands.command()
async def ping(self, ctx):
await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')
def setup(client):
client.add_cog(ping(client))
``` What does the @commands.cog.listener needs to be I can't remember
listener not capital
Why do you have an event decorator over a command decorator
Can I just remove that line?
@commands.Cog.listener()
Yes
Let's see if it works
uhm
import discord
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')
def setup(client):
client.add_cog(ping(client))
Indentation
Not it's indented inside the __init__
why both class name and command name ping
Take it out of that
And add uppercase to class names
okay
that's the convention
Yeah
still error
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')
def setup(client):
client.add_cog(Ping(client))
import discord
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.reply(f'**Pong!** {round(client.latency * 1000)}ms')
def setup(client):
client.add_cog(Ping(client))
Yes
its self.client
Ah well yeah
On what line?
what line does the error say
Where the errors tells you
10
Then go there
And look where you used client
is it possible to run a cog with a different prefix....like ik dis stoopid but i want the music commands to be run only wid >....plausible?
import discord
from discord.ext import commands
import nextcord
import nextcord.ext
class Disable(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def toggle(ctx, *, command):
command = client.get_command(command)
if command == None:
await ctx.send("Couldn't find that command")
elif ctx.command == command:
await ctx.send("You cannot disable this command")
else:
command.enabled = not command.enabled
ternary = "enabled" if command.enabled else "disabled"
await ctx.send(f'command {command.qualified_name} has been {ternary}')
def setup(client):
client.add_cog(Disable(client))
``` How would I fix this?
Fix this, fix what exactly?
Add self in the command parameters
still
No problem
@slate swan do you actually pay for winrar?
Last question 😛
wait
a tab at the @commands.has_permission right
no
oh :/
put the check above async
oh shoot I forgot
It says in the docs
check must be above async and it's case sensitive administrator
Why this happens?
←[33m[=] SamTheNoob#4854 Moved from General to Idle at [2021/Oct/11 - 02:31 PM]←[0m
Instead of writing it in yellow?
This is my code:
cprint(f"[=] {member} Moved from {before.channel.name[2:]} to {after.channel.name[2:]} at {time}", 'yellow')
The cmd doesn't support colors
Use Windows Terminal or an UX-like terminal, or don't use colors
Does anyone know how to hack wifi password using python ?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Sure 👍
wtf
ask the owner
also, discord-bots channel
Anyone know how to replace a link of what you will type for example ?howtodo then the outcome will be https://learnpython/howtodo.com
Like i need to replace before the .com
wat
await ctx.send(f"https.//learnpython/{value}.com")
Ty man rlly appreciate it
how do I get bot status?
!d discord.ext.commands.Bot.user
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
bot.user.status
got it, does that return the member's status or if they're online / on dnd / idle / offline?
just making sure
cuz I need the former
hmm
this returns if it's online
It's Windows Terminal
or dnd
Hii meh where can i learn python also what theme u using
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I open my other program and it works
yes
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
clientuser object has no attribute activity
print(str(bot.user.activity))
interesting
!d discord.ClientUser
class discord.ClientUser```
Represents your Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
yeah
wait thats a nonetype error hm
but why would you get your own activity
I need it
for a sync loop
!d discord.ext.commands.Bot.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
The activity being used upon logging in.
I just realized that you needed your own bot's activity
which you can get in code without fetching anything
it returns None
even though my bot has an activity
print(str(bot.activity))
where is that
wdym
where in the code
bot.activity returns None
bru
where did you put this line
uh
in a loop?
@tasks.loop(seconds=10)
async def sync_status():
await bot.wait_until_ready()
print(str(bot.activity))
log = bot.get_channel(botlog_spam)
msg = await log.send("Syncing status")
new = await check_db('status')
type = await check_db('type')
if str(bot.activity) == str(new):
pass
then idk
How to convert User object into Member object
u can't
so i can print ctx user roles?
why not ctx.author
what's the difference between a user and a member object
member has a guild adjected to it
from member object i can print roles etc
A member is in a guild but a user isn't
ah
i mean ctx.author.roles don't work
wat
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
hm
hm
show the whole code
it should return a member
Give me one sec
same error
That’s really strang
Yea if it’s used in a Dm then it won’t work but if it is in a server I don’t know what wrong then
lmao
because ctx.author returns a member if used in a guild ,and user if used in a dm channel
Didn't think that far.. thanks anyways
It’s something like that
@tawdry perch i did nothing abt code. it was hard to understand. im still on import discord and run bot
ok, so what did you want to make again?
a soam bot. u spam messages u will get muted and bot will send u in dms 'U r muted for 5 mins'
a spam bot?
mute srry
anti spam
ok good
ye
well start by making a simple command, with ctx argument and member argument
You may want to use this to add a muted role: https://discordpy.readthedocs.io/en/latest/api.html?highlight=add_roles#discord.Member.add_roles
This to get the role: https://discordpy.readthedocs.io/en/latest/api.html?highlight=get_role#discord.Guild.get_role
for member agument remember to use discord.Member as a type of it
@harsh mirage , wait. Actually make a on_message event with message argument. I forgot you are making a antispam alrd 😅
good, well make the on_message event with message argument
@on_message.event?
ye
ok
k
I am making a clear command(purge)
and i am running over some issues. I tried to make a custom error where it detects if the amount given isnt int and then it sends an embed.
@commands.command()
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount):
if type(amount) != int:
Error_Embed = discord.Embed(title="Error. Amount should be an integer.", description=f"Value type given: <{type(amount)}>", color=0xFF0000, timestamp=ctx.message.created_at)
await ctx.send(embed=Error_Embed)
else:
task_embed = discord.Embed(title=f"{amount} messages have been cleared.", color = discord.Colour.blue())
task_embed.set_footer(text=f"{datetime.datetime.utcnow()}")
await ctx.channel.purge(limit=amount+1)
await ctx.send(embed=task_embed)
When i am testing and i say like -clear 10 it sends the error.
amount: int, should fix it
yeah ik but i want to make a custom error
a global error handler or for specific command?
@clear.error()
#code
if type(amount) != int:
Error_Embed = discord.Embed(title="Error. Amount should be an integer.", description=f"Value type given: <{type(amount)}>", color=0xFF0000, timestamp=ctx.message.created_at)
await ctx.send(embed=Error_Embed)
else:
ok
well that can work as well
yeah but
it could be an error for mutch things
how do i detect if its a type error.
by using this
Like it requires the amount to be int not str
yeah but it could be a cmd error bc it didnt loaded or something
how do i detect the certain error
in your current code, you would do either py try: x except smth: or ```py
if smth:
#code
else:
raise SomeError
i dont think you need () for the error events deco
I'm not sure, so I just added it
mhm , its not required
othe second is just what i did
and it has the error i told u
I don't have time to fix it atm. But I recommend using a error handler
i added the event. what now?
I will be maybe back in 20 mins
what issue do u face with it?
@harsh mirage
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = 'your prefix')
ok ty
ok
@slate swan but that means i will run the bot with bot.run or smth like that instead of
client = MyClient()
client.run('TOKEN')
@harsh mirage
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print("Bot is ready")
client.run("")
ty
I'm doing an anti ghost ping command, the code is only right that when I try it the bot doesn't give an answer.
here the code:
async def on_message (self, message):
word_list = ['@everyone', '@here']
# don't respond to ourselves
if message.author == self.user:
return
messageContent = message.content
if len (messageContent)> 0:
for word in word_list:
if word in messageContent:
await message.delete ()
await message.channel.send ('Hey don't ghostping.')```
wym?
how can i send '_io.BytesIO' object in embed.set_image()?
Anti ghost ping is useless because even if you delete the message it still sent the ping
!localfile
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
thank you my dear, but is there any way to do that without saving image to file?
discord.File(bytesi_object) and send it
how can I send it as an attachment?
discord.File(bytesi_object, filename="test.png")
embed.set_image(url="attachment://test.png")
await Messageable.send(embed=embed, file=file)```
thank you!
can someone help me pls why is it displaying this error
channel.type
Thanks <3
So I am trying to make a bot give 1 of 4 roles to everyone on the server. I got everything, but I am facing a problem where I am unable to make it an even spread of the roles. One the roles sometimes ends up with a lot higher percentage of people with the role than the others. Does anyone have any ideas?
how do i know if a cog is not loaded?
@commands.command()
async def modules(self,ctx):
embed=discord.Embed()
for co in self.bot.cogs:
embed.add_field(name=f"{co}", value=f"{'{}'.format(utily.done) if co else '{}'.format(utily.error)}", inline=True)
await ctx.send(embed=embed)
well.. you can't actually check, there's no method nor attribute or property that returns True or False whether the cog is loaded or not
but what you can do is try to unload it and load it back in a try/except, if the cog is already unloaded it will raise an error which will basically tell you that the cog is not loaded
really bad option but that's the only way you can do it without storing your unloaded cogs somewhere when you unload them
personally i'd have a var for each role that's the type bool and when doing the for loop to add the roles i'd check if the previous value is False or True, and when reaching the last of the 4 roles it resets all 4 to False
you censored too much of what's raising the error, also it's a syntax error, you're expected to be able to fix those yourself when attempting to use dpy
or when making something a little bit more advanced in general
it was my bots token
ik
but you censored even the ending string
it was simple coding
and u can't fix that "simple coding"
¯_(ツ)_/¯
I started today lol
you should start by learning python not with a discord bot
but anyways, only censor your token not the ' or "
and then send again
I stopped making it
why 😂
js is the way to go
python is easier than js but u do u
ik but my friend says it has lil to no syntax errors
syntax errors are usually really easy to fix
even js can have syntax errors
ik that's why I'm just gonna either learn LUA
or stop
then keep with LUA
since LUA is really fast and the syntax is somewhat similar to python too making it not all that hard to learn
Lua is low level too
yeah
even has a discord wrapper if @slate swan is interested in that
what?
Discord.js doesn’t cover everything too
how can i get rid of the ['']
i have {error.missing_perms}
just do ', '.join(list)
Anyways, I was wondering if it's possible to call another command by doing a command.
This has nothing to do about aliases, I just want to invoke a command with certains parameters is that possible?
Yes you can
How do we do that exactly?
await bot.process_commands(message) or await command_function_name(params)
Hello, I need help with a discord bot. Though, it's JavaScript, if anyone knows js here please help, if not, can you recommend a server that can help me with my js discord bot?
so there is a way or
Thanks man
you can do .replace("['", "").replace("']", "")
!d str.replace
str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
like await ctx.send(str(error).replace("['", "").replace("']", ""))
btw I need to precise there that it's inside an error command.
It goes by this. However, the function cannot be recognize since I put it in another function.
...
elif isinstance(error, discord.ext.commands.MissingRequiredArgument): await function(self, ctx, ctx.author)
like you have py @commands.command(name="haha") async def not_haha(self, ctx): ...
you use py elif something: await self.not_haha(ctx)
yuh
I mean like if I'm missing an argument in not_haha it will cause an error of missing argument
however, I want for the missing argument to redirect the argument to the ctx.author
Geez I had 50 if statements trying to hard code it for each possible combination. I ended up using a list that assigns a role based on random choice. It then removes that option from the list, and then refills it when it hits 0. Thanks a ton for the help. Even though I didn't use your strategy exactly it pointed me in the right direction that I needed.
confusion
why not
becuase it’s bad?
then how better?
str.join like you suggested before
¯_(ツ)_/¯
what?
OMG I DID IT! Thank you so much
?? error.missing_perms is a list for him
uh he is using this... i just idk im stupid bye
okay
Does anybody have some sort of function, which makes all "->" on the same line?
how do you edit a past message knowing its message id?
TextChannel.fetch_message -> Message.edit
ohhhhh ok ty
what do you mean?
elif message == "true" or "True" or "yes" or "Yes":
try:
db.update_one({
"guild_id": ctx.guild.id},
{"$set": {"guild_embeds": True}})
return await ctx.reply('turned **embeds** on!')
except:
return await ctx.reply('failed to turn **embeds** on!')
elif message == "false" or "False" or "no" or "No":
try:
db.update_one({
"guild_id": ctx.guild.id},
{"$set": {"guild_embeds": False}
})
return await ctx.reply('turned **embeds** off!')
except:
return await ctx.reply('failed to turn **embeds** off!')
else:
return
its automatically setting it to true
!orgotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
i think its also time to learn about .lower()
??
if message.lower
that's all ik
If message is a discord.Message object you would want to do, if message.content.lower() in ('true', 'yes'):
how do i make a command group in cogs
commands.group
File "main.py", line 41, in config role3 = ctx.guild.get_role(config["3"]) TypeError: 'Command' object is not subscriptable
This doesnt make any sense, config is a dictionary, how come all of a sudden this doesnt work, what command object is this IDE smoking, there is no object its just an integer under this name. Im lost...
This is literally all the config.json file has
{"4": 0, "3": 0, "2": 0, "1": 0}```
0 Its giving me aTypeError, shouldn't it be giving me RoleNotFound or smth
Is config defined in your main file?
yeah
Its a json file remember?
What is it defined as though
If you want to do that I would just make a local dict inside of your py file and then keeping the code the same since it isn’t that much information needed to store inside of another file
uh yeah lemme check
config = {"4": 0, "3": 0, "2": 0, "1": 0}```
wait if i defined it outside of a function
would it still work inside?
of the*
Cogs or main file?
main
Just put what I did at the top of the file
Lmk if that works
oh ok
wait what no
why would i want that
What are you trying to do
when the code restarts
its gonna default back to that
it's in the var name "config"
Are you gonna store stuff inside of the dict?
making a configurable settings
config is a command
^
wait fr?
Make the variable inside of the function
oh
that’s what the error says?
are you even loading the json file
yeah but outside of the function
ill try inside rq
What mode are u opening the json in
Read right?
lol im not stupid obv read
Ok good LOL
Yesterday I quick made a bot that automatically converts incompatible file attachments to versions with built in Discord players, thought some people could find it useful!
Not really what this channel is for
if it’s discord bots related i think it’s fine
i got an error: no module named 'discord'. how do i fix this?
install discord.py
how in cmd prompt
do you know how to use pip
also do i need to download anything except python and sublime text
oh so you’re new to python?
type the following in command prompt: pip3 install discord
no dont necessarily need sublime text
but no youre good
yeah just started learning python yesterday and doing discord bots today
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
skid
Lol about a year ago I started python w discord bots to, while I was learning I learned a lot of python so I think it’s a great start imo
it’s not a great start
unless you knew another language before python and you didn’t really need basic stuff
how can i get the estimates time it will take to give all members a role
depends on your delay.
gives all members a role and calculate the time it took
he wants eta
there is no way without actually trying it no?
if you, await asyncio.sleep(1) between each role add, then multiply the amount of members by that
maybe by moer like 1.1 depends on latency
or like 1+bot.latency lol
and round it and say itll take that much
huh
Question:
How could I make an input user based so for example
value = '0'
@client.command()
async def change(ctx, value):
print("value")
#how could I change the variable value based on the input for the whole program
Bots get rated limited when adding roles right
this will be a 1 server bot so I only need it to change for the whole program
I believe yes
Then the above questions answer would be the amount of members divided by the rate limit
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
i need help
@bot.event async def on_ready(): async with aiofiles.open("ticket_configs.txt", mode="a") as temp: pass
the one that starts with "async with aiofiles.open"
do functions help decrease the speed? like
async def command(ctx, user):
def myFunction(id, user)```
instead of
```py
async def command(ctx, user):
do the thing in the function, but in the command```
nah not that
im tryna get a ticket system
Are you getting an error?
yeah
the aiofiles is what im having a problem with
hold on lemme show
i already have asyncio
LOADED Music.py Ignoring exception in on_ready Traceback (most recent call last): File "C:\Python\lib\site-packages\discord\client.py", line 333, in _run_event await coro(*args, **kwargs) File "C:\Users\mrshe\Documents\ZeroX The Flow\run.py", line 16, in on_ready async with aiofiles.open("ticket_configs.txt", mode="a") as temp: NameError: name 'aiofiles' is not defined
@final iron
?
I'm panicking so hard right now. My cogs used to work perfectly, but now it seems like none of them is working. I don't know why. This is what I have right now. Basically it takes all python files in my cogs file directory and loads them.
but somehow in my cogs repertoire, there's this, and somehow it loads it twice.
_pycache_ is normal
I have the exact same thing
then i don't know why my cogs don't wanna load anymore. im so upset
it checks in cogs then it goes in pycache to check them
@client.event
async def on_member_remove(member):
channel = client.get_channel(896475085534289940)
print("hi")
await channel.send(f"**{member.mention} has betrayed the Miners's order.**")```
I tried the same code on on_member_join, it works fine but why not on on_member_remove?
@opal sonnet
.
how can i make it so only certain users can run a command
do you have intents
add a command check
does it print hi
DISCORD_GUILD={your-guild-name}, how this command work? And does it work on multiple guild?
I wanna die, all my cogs file don't work anymore.
Well you defined the command so you know how the command works
Show the extensions and the loading script
Nope at all i just seen it on a tutorial
It's there.
I haven't changed this.
It started to not load once I was adding another test.py file that I've dragged in my cogs file.
I don't know what to do
Then look at the tutorial again or ask the creator of the tutorial
Show what this file looks like
Okay thanks
None of the cogs want to load.
Error?
It always either loads them or errors
If you have a bad error handler that suppresses unknown errors fix that first
I mean, unless if you force to load a specific class of commands, it just cannot find it.
Hmm we can always try the good old print debugger
Go to the line of load_extension
One line before add a print
And one line after add a print
I did this to print my cogs = []
See if they both get printed for every extension
Wut?
It prints it twice.
So it prints the one before and after
And that for EVERY extension?
@bot.command()
async def price(ctx, price: int):
if price < 100:
value = {price}*.40
hi = discord.Embed(description=f'`>` Price of {price} million is {value}', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=hi)
if price > 100:
value2 = {price}*.35
he = discord.Embed(description=f'`>` Price of {price} million is {value2}', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=he)
else:
error = discord.Embed(description=f'`>` Please enter valid price', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=error)```
```py
Command raised an exception: TypeError: unsupported operand type(s) for *: 'set' and 'float'```
i have no clue how to fix this ngl
what line is the error?
.35 isn’t valid
0.35 is valid
ohhh
Sebkuip can u check my dm
well, that fixed it but now im getting TypeError: '<' not supported between instances of 'str' and 'int'
EVERY extensions
Then you have to make them both ints
Then they should be loaded
because it goes in the pycache and checks it too.
Delete the pycache then
nevermind, fixed that but now it is just saying it's not a valid number
I'll try it when im back on my pc
tasks.start()
@bot.command()
async def price(ctx, price: int):
if price < 100:
value=float(price)*0.40
hi = discord.Embed(description=f'`>` Price of {price} million coins is ${value}', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=hi)
if price > 100:
value2=float(price)*0.35
he = discord.Embed(description=f'`>` Price of {price} million coins is ${value2}', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=he)
else:
if type(price) is not int or float:
error = discord.Embed(description=f'`>` Please enter a valid price', color=0x8379da, timestamp=ctx.message.created_at)
await ctx.reply(embed=error)```
so it sends the correct price, but then sends error message, idk lmfao
ok ty
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
and use isinstance() for checking types
ah
@valid niche Hey you still there?
I managed to fix my problem, although I just don't know why it doesn't wanna work anymore
so basically, everything works until client.load_extension. I'm not sure why it doesn't wanna take the variable there which is kinda weird. If you name the extension explicitly, it will work however.
when you were installing python, you didnt add pip to path
wot does tat mean
pip install discord
Try python3 -m pip install discord
y not just load the extension automatically instead of having to append them to a list and then load them?
try pip install discord
Won't work
The correct way
what
he tried pip3
restart your pc
??
