#discord-bots
1 messages · Page 520 of 1
!customhelp
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Can someone send me a full code on an application bot
because currently my server needs one
So it would be a huge help if someone did
When you guys say post code do you mean the entire 312 line code? Or the command?
Sorry I’m new to this
Just the command that errors
@slate phoenix that
people are here to help with code no one will spoon feed
Can you send the code for the command not the error
my bad
My bot is returning py <Message id=895137648736337920 channel=<TextChannel id=813823051774165042 name='📝general' position=5 nsfw=False news=False category_id=789941689791283210> type=<MessageType.default: 0> author=<Member id=868156490022789130 name='Water Boat' discriminator='8161' bot=True nick=None guild=<Guild id=788123028302594079 name="The best gaming server (don't leave)" shard_id=None chunked=True member_count=26>> flags=<MessageFlags value=0>> for some reason
Stats of the channel
Code?
that’s still not the code for the command
Hey @buoyant sage!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
codes 312 lines wont let me send
use that link
like the
@bot.command()
async def …..
@commands.command()
async def command(self, ctx, member: discord.Member):
msg = await ctx.send(f"a")
await ctx.send(msg)
await asyncio.sleep(1)
await msg.edit(content="test")
@slate phoenix hope im not pissing you off lol
why did u send 2 thingies
you’re fine dw about it lol
Oh never realized that
what u tryna do tho
I have it there for something im planning on doing
def send_keepalive(self):
"""
sends PULL_DATA messages from all virtual gateways
:return:
"""
self.last_keepalive_ts = time.time()
for gw in self.vgateways_by_mac.values():
data, addr = gw.get_PULL_DATA()
self.sock.sendto(data, addr)
def __del__(self):
self.sock.close()
@commands.command()
async def command(self, ctx, member: discord.Member):
msg = await ctx.send(f"a")
await asyncio.sleep(1)
await msg.edit(content="test")
``` try this I guess
Looking at the error you’re attempting to use the attribute “sock” on the class GW2Miner but it doesn’t exist
hmm thats odd. maybe missing files? there are around 5 others running this script with no issues. it has to be me, or files missing?
if you had modules missing the error would show that, did you write this class or did you download/copy it?
cloned from github
What I would try to do is delete the file that’s giving the error and clone it again it’s possible you may have accidentally delete a line or something
ok so delete the enitre clone, re clone, then try command?
I would try that yeah
wouldnt it be from .src import messages ?
yeah
what do you mean?
from .src import *
change that line to what you said?
change from src import to from .src import
ok will try now
show full traceback
show it lol
ive put .src
any one help
self.bot.wait_for
..
What's the maximum number of characters you can use in an embed?
lol
Who is this bot
Does anyone know how to improve select menu in dislash.py?
Can one of you all make a wrapper that uses Pydantic plz instead of just forking and renaming imports? Plz K Thx
try it?
@client.command()
async def test(ctx):
msg = await ctx.send(
"This message has a select menu!",
components=[
SelectMenu(
custom_id="test",
placeholder="Choose up to 2 options",
max_values=2,
options=[
SelectOption("Option 1", "value 1"),
SelectOption("Option 2", "value1"),
SelectOption("Option 3", "value 3")
]
)
]
)
inter = await msg.wait_for_dropdown()
labels = [option.label for option in inter.select_menu.selected_options]
await inter.reply(f"Options: {', '.join(labels)}")
Anyone knows how to change this I mean when clicked it shows an embed
explain
Me?
U asked me?
did i?
What u mean I don't understand can u help me in that prob
gw_configs/ doesnt exist?
wdym "it shows an embed"
i guess not, i dont see anything named that
then you should fix that
missing file?
looks like a folder
i had a hunch there was a folder missing
I mean when I run this code it does a select menu and when I clicked on option it shows selected option 1 or the option number. I want to change this to embed that means when I clicked on option 1 it should show an embed that I created and when clicked on option 2 it should show the other embed I create that's what I mean u know how to do like that?
Can u say
Ok
code doesnt have that gw_config in it.. is it for sure a folder missing?
args.configs
oh ok so thats the name of folder that is missing
any idea on how to find it if its not in the github file? i wonder how ppl are running the code with that missing folder!..
Finished?
i need to find it
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_slash_command_error() takes 1 positional argument but 2 were given``` ```py
@cog_ext.cog_slash(name='pfp',
guild_ids=[479997589790523405],
description="This is just a test command, nothing more.")
async def pfp(self, ctx: SlashContext, member : discord.Member):
await ctx.defer()
await ctx.send(member.avatar_url)```
The only thing I'm giving it is the member to get the avatar from
Oh so tales so much time I think hm
i have a lot of files
what did i do wrong? when i do /ping it doesnt work
Oh ok
Sorry your message was deleted @sonic flax. Something in the code triggered our invite filter.
why use bot and client ? choose one
ur ping command is using client and the command prefix is "prefix" not "/" so obv it wont work
any clue why this isnt working?
@client.event
async def on_reaction_add(reaction, user):
if reaction.emoji == ':clap:':
print('hi')
str( reaction.emoji)
Hey, super new to discord py. I have a User object. I want to know that user's member name inside a specific guild. How would I go about converting the User object into a Member object?
theres a user object? i didnt know that
I used fetch_user
nop
hm
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
this is what's printing out
ok that's what I thought, but it keeps coming back as None
discord.Object(id=user.id).display_name
Then use fetch
ahh so there's a fetch_member?
so many errors
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
ok but where would I tell it which guild?
for that you should use guild.get_member
or fetch_member
your wish
!d discord.Guild.fetch_member
await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
Well they have already stated get_ is returning None so they likely have to
fetch_member works here. What would be the reason that fetch works but get doesn't?
oh it's something to do with bot permissions?
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.now().timestamp()
reason = "Feature Anti-Nuke | Banning Members"
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.now().timestamp() - start), 3)
log = await r.text()
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.bot.get_channel(892973735802449943)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user))
you needed Intents.members for get_member as it's getting the member from bot's cache
okay so this will not work at all, no error no nothing
ahh ok. Aside from having to change it, is there an advantage to get over fetch? Would get just be faster?
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
get_x should be faster
i'm not using that
I can read, but its built it and likely a better option
i'm trying to use whatever's faster
ok, thank you so much! I'll see if I can get it working with Intents/get_member
any clue why this isnt working?
@client.event
async def on_reaction_add(reaction, user):
if reaction.emoji == ':clap:':
print('hi')
it is an event called if a person is banned not a command
...
anytime 
Make your own wrapper based on that then. Otherwise your gonna just be reinvented something already provided to you
use await member.ban(reason=reason)
if I'm using Client instead of Bot, how would it be different?
nvm got it
nothing, Bot will just allow you to use commands extension.
no changes to cache, intents, etc
so Client also has an intents= parameter?
yes
nice!
Bot inherits Client, and Client has all the api stuff
File "c:\Users\OneDrive\Desktop\featured(bot)\cogs\events.py", line 13, in on_member_ban
start = datetime.now().timestamp()
AttributeError: module 'datetime' has no attribute 'now'
i got this error
datetime.datetime.now()
try datetime.datetime or from datetime import datetime
thx
intents = Intents.default()
intents.members = True
client = discord.Client(intents=intents)
so I have it like this, and get_member is still coming back with None
Did you enable em on your dev portal
yeah
try chunking the guild, await guild.chunk()
dpy should chuck it at startup, but who knows

in discord.utils.get is it ctx.guild.roles or ctx.server.roles?
why this error?
yay it worked
i am making a mute command
guikd
guild*
ok ty
?
from discord.ext import commands
is this using replit??
already added
nope
show all code pls
in dms?
alr
Get file?
@commands.command()
@commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member, reason = None):
if reason == None:
reason = 'No reason provided.'
role = discord.utils.get(member.gulid.roles, name='Gulag')
role2 = discord.utils.get(member.gulid.roles, name='Nerd')
await self.bot.remove_roles(member, role2)
await self.bot.add_roles(member, role)
embed=discord.Embed(
title="User Muted!",
description=f"{member.mention} was muted by {ctx.author.mention}. Reason: `{reason}`! Do `#unmute <@{member.id}>` to unmute the user.",
color=0xff00f6
)
await ctx.send(embed=embed)
if feel like this command is not working because of the discord.utils.get but i just want some verification
also it is an CommandInvokeError
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
bot.remove_roles?
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
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 removed [`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.
!d await inter.reply
!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.
Check if role is not None for can add it.
if not muted_role:
create role
Hey @slate swan can u help me in onething?
I will try
@client.command()
async def test(ctx):
msg = await ctx.send(
"This message has a select menu!",
components=[
SelectMenu(
custom_id="test",
placeholder="Choose up to 2 options",
max_values=2,
options=[
SelectOption("Option 1", "value 1"),
SelectOption("Option 2", "value1"),
SelectOption("Option 3", "value 3")
]
)
]
)
inter = await msg.wait_for_dropdown()
labels = [option.label for option in inter.select_menu.selected_options]
await inter.reply(f"Options: {', '.join(labels)}")
how to change this?
I mean when I run this code it does a select menu and when I clicked on option it shows selected option 1 or the option number. I want to change this to embed that means when I clicked on option 1 it should show an embed that I created and when clicked on option 2 it should show the other embed I create that's what I mean u know how to do like that?
Hi, i am trying to get the list of channels in certain category, but this is not working, idk why
@slate swan
and when i type 1 it will show me: <property object at 0x0000015DAF19DE00>
category.chanels
discord.CategoryChannel is just a class you aren’t printing anything except the memory location of the object
oh
library?
!d discord.CategoryChannel.channels
property channels: List[GuildChannelType]```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
Dislash have event for this interaction?
I mean something like on_select_menu?
message.channel.category.channels
slash = InteractionClient(client)this?
No
Nothing else
Only this and code
get_channel?
I dont use this library sry
Oh then what else u use for this?
You are new in python?
yeah
category = guild.get_channel(category id) # category id for take the channels
for channel in category.channels:
print(channel.name)
Which library u uses for buttons/ selectmenu
?
!pypi discord-components
Ok
define the guild
Like category
But here is one more easy way to do that
message.guild
discord.errors.InvalidArgument: Could not resolve appropriate move position
why u.U
Hi, how can i make the bot send a message after anyone use 5 commands, for example, a user make 5 bot.commands and the bot un the 5th command send an extra message with an anounce.
Anyone know?
use on_command event
How can I do that?
I need to check the docs for the spelling.
Though, they meant the discord.on_command. But for what you need, it would be better to check if the command has passed all checks and actually executed.
your quiting what?
how to make a (cmd enable or disable) cmd ?
post the error
Channel is defined?
!d discord.VoiceChannel
yes check the args
got what
I already told u the errors though
eh why 2 async def in 1 @bot commands?
didnt u have a channel arg though
but you are trying to create 2 cmds
I'm reading the docs, but dont find how to make that i want.
I think to make a @tasks_loop
And take a random channel of the guild and send it to this channel.
I already want to make send this message after x quantity of @bot.commands()
remove the 2nd line, write afk instead of move in the 3nd line,fix the indents.
You can use the on_command event and save in a database each time someone uses a command and then check whether they reached 5 commands yet.
u cant have and u dont need 2 async def to make a cmd bro
i made a on_message event
but it is only working in 1 server
is it possible to do two components with the same message EX: Select menu and buttons ?
Please Tag to reply
Code?
how can i send a message in a channel if the user does not nave a specific permission? (sorry for my grammer)
Not really getting what are trying to do here but if you want the bot to send a message if it doesn't have permissions to do that then its impossible, the users has to select to specify the permissions.
Add a check tot he command and use a try except I guess
yes ?
Oh then u can really really help me playing help
Ok whats the problem ?
I need to add select menu when I clicked on one option it should show an embed that I made and when clicked on other option it should show other embed
Like that
ok should it edit the message or send a new one
What ?I didn't getu
Like when you click the option should it edit the message and replace it with an embed or send a new one ?
Edit
ok then wait
Ok
how do I trigger a command when someone boosts a server
@slate swan py while True: event = await self.bot.wait_for("select_option", check=None) label = event.component[0].label if label == "": #enter the label or value of the selct menu options await event.message.editembed=em1) #em1 is the embed you want elif label == "": #enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want elif label == "":#enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want elif label == "":#enter the label or value of the selct menu options await event.message.edit(embed=em1) #em1 is the embed you want
Thnx
Thnx very very much
welcome 😉
What should add above while true:?
@client.event
async def on_message(message):
if "MessageType.premium_guild" in str(message.type):
await message.channel.send("Thanks for server boost")```
thanks
Welcome 😉
@bot.event
async def on_message(message):
if message.content == "!mute @Riad#1922":
user = await message.guild.fetch_member(760010546728402975)
guild = message.guild
mutedrole = discord.utils.get(guild.roles, name = "Muted")
await sleep(5)
await user.remove_roles(mutedrole)
await message.channel.send("Did you just escaped a Mute @Riad#1922?")
await bot.process_commands(message) ```
why this is working in only 1 server?
@leaden anvil What should add above while true:?
select menu and embeds you want
Oh ok
does it it any error if used in other servers ?
nope
then maybe the message.content doesnt match
make sure it be like this ```py
@commands.command(name='select-test')
async def select_test(self, ctx):
await ctx.send("We are testing selects!",
components=
[Select(placeholder="Choose what you want to see!",
options=[
SelectOption(
label="Option 1",
value="option1",
SelectOption(
label="Option 2",
value="option2",
),
])]
)
e1 = Embed(title="embed1", description="a really exciting embed")
e2 = Embed(title="embed2", description="a really exciting embed")
e3 = Embed(title="embed3", description="a really exciting embed")
while True:
try: # try except is not required but i would recommend using it
event = await self.bot.wait_for("select_option", check=None)
label = event.component[0].label
if label == "Option 1":
await event.message.edit(embed=em1))
elif label == "Option 2":
await event.message.edit(embed=em1))```
@slate swan
@oak warren
the muted role is present in both the servers ?
hmm
ok do this add a thing to print the server name just after if message.content ==
and then try
if it prints then something else is wrong
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
python 3.10 is unstable?
OK Thnx once again no limits for thnx
import discord, os, time, random, asyncio
from datetime import datetime
from discord.ext import commands
class commands(commands.Cog):
def __init__(self, client):
self.bot = client
os.chdir("C:\\Users\\\ASUS\\Desktop\\john-cena\\cogs")
@commands.command()
@commands.is_owner()
async def bal(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet = users[str(user.id)["wallet"]
await ctx.reply(f"{ctx.author.name} balance is: {wallet}")
@commands.command()
@commands.is_owner()
async def sc(ctx, user: discord.User, *, jum):
users = await get_bank_data()
user = ctx.author
await ctx.send(f"credit social earned! {jum}")
users[str(user.id)]["wallet"] += int(jum)
with open("mainbank.json", "w') as f:
json.dump(users, f)
async def open_account(user):
users=await get_bank_data()
with open("mainbank.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("mainbank.json", "w")
json.dump(users, f)
return Trues
async def get_bank_data():
with open("mainbank.json", 'r') as f:
users = json.load(f)
return users
i tried to make a discord economy bot but there is an error, any help?
error text:
Traceback (most recent call last):
File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 846, in exec_module
File "<frozen importlib._bootstrap_external>", line 983, in get_code
File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\Users\ASUS\Desktop\john-cena\cogs\economy.py", line 17
await ctx.reply(f"{ctx.author.name} balance is: {wallet}")
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ASUS\Desktop\john-cena\main.py", line 36, in <module>
bot.load_extension(f'cogs.{filename[:-3]}')
File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: SyntaxError: invalid syntax (economy.py, line 17)
update: its line 16
your welcome 😉
how can i get who was banned using an event and AuditLogAction.ban
!d discord.AuditLogAction
class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
Is line 16 wallet = users[str(user.id)["wallet"]?
Yes like that
Me using that
Well, that has an issue.
ye
how to get time in 30s
wym
I think he means that he needs a text to time converter
You do it like this:
time = "30s"
Amount = time[:-1]
Unit = time[-1]
Amount will be the number, unit is the time unit
There can be other way but i prefer this to do tempban and tempmute command
So this was a question that I had,
its about a method called os.execl
I made a simple command that can reload a program when it is called, I used to to restart discord bot programs, but some devs said that it should be not be used, but I wonder why because they didn't tell me why
import sys
import os
async def restart_program(self):
python = sys.executable
os.execl(python, python, * sys.argv)
@commands.command()
@commands.is_owner()
async def restart(self, ctx: commands.Context):
await ctx.send("Restarting... Allow up to 20 seconds")
await self.restart_program()
?
@leaden anvil is here any problems?
Read up that message
You aren't getting the data from the dict correctly. You are doing users["1"["wallet"] taking user.id as if it's equal to 1.
like we pass >mute @winged charm 30s then here how i can get 30 and s seperatly?
@placid skiff
Read up the message u replied
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
banned = logs.target.id
rbanned = self.bot.get_user(banned)
.
your error is pretty much self explanatory
and i am trying to unban rbanned and it is returning NoneType
read the error
ohh ty
can't really see the code can you send it
Then rbanned is not in your bot's cache. Try fetching the user instead of getting it.
rbanned is returning NoneType, any idea why
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
ohh thx you
I don't see any use of fetching the user, though. You already have it. logs.user returns the User object.
I know that this is not rilevant to discord.py directly but there is a way to check if a string is formatted nickname#id like?
after i fetch do i use get?
after i do this do i use get??

if you hide it then how will you access it?
trying to get the user that was banned
Don't use heroku to host a Discord bot.
and that 
which is target correct
Fetching the user will return a discord.User object, meanwhile logs.user also does. So you don't need to fetch the user anyways.
Anyone?
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
banned = logs.target.id
rbanned = self.bot.fetch_user(banned)``` so in this
what is the user that banned vs the one that got banned
What is logs.target??
the user banned
Then you already have the user object, why are you trying to get it again??
that's why i'm asking which variable is the person that banned vs the one who got banned
Target is the banned user.
so i'm guessing your saying logs[0] is the user who banned
logs.user is the responsible of the action, logs.target is what/who the action was made on.
so that should be correct??
no, thats the last log
What is "that"?
..
No.
how so, i am not understanding what you are saying
name = "scoopy"
myname = name
What's the difference between name and myname?
nothing
Exactly same with banned and rbanned.
ohhhh
how i can check if a message content only have mention of my bot ?
so how am i supposed to get the member to unban
You don't need rbanned.
!e py logs = ["3rd", "2nd", "1st"] print(logs[0])
@lament mesa :white_check_mark: Your eval job has completed with return code 0.
3rd
message.ismention iirc
banned is the user that got banned, just removed the id attr.
?
Let me check
yes
so just logs.target
i host that bot
anyone pls ?
Check if message.content is equal to bot.user.mention.
i want to hide my bot token @dapper cobalt
Yes.
where do you host your bot
heroqu
Don't host it on heroku.
now i am getting the 'User' object has no attribute unban
use heroku's config vars
i also do like this
yha i do
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
that should be enough
that how will i write that screat in my main file
!d os.environ
os.environ```
A [mapping](https://docs.python.org/3.10/glossary.html#term-mapping) object representing the string environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.
This mapping is captured the first time the [`os`](https://docs.python.org/3.10/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in `os.environ`, except for changes made by modifying `os.environ` directly.
This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3.10/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
i have await banned.unban(reason)
not working
that's prolly why
please send the code
mm
it's like:
token = os.environ['token']
bot.run(token)```
Ik, is user just the id??
ok lemme check
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
yes it is
unban takes a user object, not just the user's ID.
so i do await guild.unban(banned, reason="my reason")
from this after removing rbanned
not working
Yes.
Try to print the message.content.
ok
ok thanks it is workking
How do i fetch a role in a guild?
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Yes. It's stored in the bot's cache.
could someone help me install the new discord components
If you don't show the error you're facing, no we can't
KASH
Similar to "catch".
I don't think so
@commands.command()
@commands.guild_only()
async def github(self, ctx):
role = ctx.guild.get_role(895210078133710929)
await ctx.author.add_roles(role)
if ctx.author.role:
await ctx.author.remove_roles(role)
embed=discord.Embed(
description='Removed the `github` role!'
)
embed.author(name=ctx.author, icon_url=ctx.author.display_avatar)
embed.timestamp=datetime.utcnow()
await ctx.send(embed=embed)
``` ```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "/home/runner/db/cogs/errors.py", line 46, in on_command_error
raise(error)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'role'
``` it isnt letting me add a role to the author for some reason?
i don't know if adding/removing roles works for the author though (ctx.author)
help
the
ffmpeg on discord.bot
doesn't act
[youtube] wDgQdr8ZkTw: Downloading webpage
[youtube] Downloading just video wDgQdr8ZkTw because of --no-playlist
it is importing song to bot's mic with youtube_dl
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
commands.Context.author returns a discord.Member object, which has remove_roles and add_roles methods.
!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.
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
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 removed [`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.
hm
And, discord.Member object does not have a role attr, though, it has roles which returns a list of discord.Role object(s).
I just did if role in ctx.author.roles instead of ctx.author.role because apparently author has no attribute role
how can set in channel rules, a single member can change its name?
Give manage channels permissions to only that member.
how
@bot.event
async def on_member_update(member):
role = bot.get_role(864830377741647872)
if user.id == 650516102488784934:
await member.add_roles(role)
Uhh am i doing anything wrong why the bot didn't add the role
What is on_role_remove? I'm pretty sure that's not an event.
Can some body help me: Ok I want to edit a message after a select menu event is done but it gives me the error Command raised an exception: TypeError: feedback() missing 1 required keyword-only argument: 'self' why is this I specified self already here is the code: https://paste.pythondiscord.com/vowunuyiwu.csharp
self must be your first kwarg.
There is no such thing as on_role_remove, on_member_update is the event called when a members roles are updated
Oh
Alright
You also need the role object to add roles
That is just the id
ok
role = guild.get_role(864830377741647872) change it to that
Also the .add_roles method is only on the member
Not the guild
@commands.command()
@commands.guild_only()
async def role(self, ctx, roles):
github_role = ctx.guild.get_role(895210078133710929)
status_role = ctx.guild.get_role(895210111625224222)
if roles == "github":
if github_role in ctx.author.roles:
return await ctx.author.remove_roles(github_role)
embed=discord.Embed(
description='Removed the **github** role!'
)
embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
embed.timestamp=datetime.utcnow()
await ctx.send(embed=embed)
await ctx.author.add_roles(github_role)
embed=discord.Embed(
description='Gave you the `github` role!'
)
embed.set_author(name=ctx.author, icon_url=ctx.author.display_avatar)
embed.timestamp=datetime.utcnow()
await ctx.send(embed=embed)
``` this is my code to remove/add a role but it works fine but when the bot removes a role it doesnt send the message. Can anyone tell me why?
this is why
hm
return means it returns from the function
it removes the role and exits out from the function
so i should put return at the bottom of the if statement?
Alright
thanks it worked sherlock
just remove the role and then send corresponding message, return isn’t needed in this case
async def on_message(message):
if message.content == "#mute @Riad#1922":
user = await message.guild.fetch_member(760010546728402975)
guild = message.guild
mutedrole = discord.utils.get(guild.roles, name = "Muted")
await sleep(5)
await user.remove_roles(mutedrole)
await message.channel.send("Did you just escaped a Mute @Riad#1922?")
await bot.process_commands(message)```
this code is not preventing probot's mute . why?
if message.content == "#mute <@your_id>" or message.content == "#mute <!@your_id>":```
i know
it is just displaying my name on discord
in my code it is the id
and is that sleep(5) is asyncio.sleep()?
nope
the sleep is fine
i figured the problem
mee6 and probot creates 2 different muted role
but when my code tries to remove it ,it thinks that it has to remove the role that mee6 has created
so thats how it doesnt work
can any one tell me how can i fix this problem?
Ok so I am getting a exception when I run the script 'NoneType' object has no attribute 'split' why is the since if I do a select menu without the event it works perfectly fine ?
Share the code that runs u that error
script py @client.group(invoke_without_command=True,) async def feedback( self, ctx, *, text=None, ): try: text = text.split("|") report = discord.Embed(color=0xFFF868) report.add_field( name="Pending Confirmation", value=f"{text[1]} #Tittle \r {text[2]} #Description", ) await ctx.channel.send(embed=report, components=[ Select( placeholder="Where to post", options=[ SelectOption(label="Bugs", value="B"), SelectOption(label="Commands", value="C"), SelectOption(label="Suggestions", value="S"), SelectOption(label="Other", value="O"), ])] ) while True: event = await self.client.wait_for("select_option", check=None) label = event.component[0].label if label == "B": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "C": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "S": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) elif label == "O": await event.message.edit(components=[[Button(style=ButtonStyle.red, label="Discard", custom_id="n"),Button(style=ButtonStyle.green, label="Send", custom_id="y"),]]) except: await ctx.reply("Please enter `/feedback format` to check how to format.")
Essentially the variable u are trying to split is not a string object
It occur on text = text.split("|")
the split occur in value
The text is None as default
So if you don t pass any values to text it is a NoneType object
But I did here
without the event
so why ?
ok
Well, that sure is weird
Just to try, before the try - except write this:
text = ctx.content.strip("/feedback ")
ok
error 'str' object has no attribute 'content'
What the hell?
Your ctx is passed as a string? Bruh?
yeah py is weird sometimes
It is a cog am i right?
Can you write the whole code on paste bin or something and send the link to me?
Well no problem, copy the whole file somewhere and send it to me xD
Ok i guessed it right
You re using self but you re not inside a class
So your self parameter actually is the context of the command
And ctx is the argument you pass after you write the command
Also, why you have a comma after your (invoke_without_command=True)?
is there anyway to use express-py and make my bot send a DM when it gets an upvote? or use webhooks
Why not using the library of the bot list?
i am sorry but idk about that actually the site helpers just told me to use votewebhooks for this purpose
!pypi dblapi
Discord Bot List API Wrapper, customised for use in discord.py
hmm
thanks
I'll see what I can do after reading docs
This library is actually so bad xD
No documentation and doesn't support webhook events
true , no docs
well , if they ask in their server it will be helful
I don't even think this bot website has good api wrappers at all
thats the only wrapper they designed
oh wait
there are no docs
yeah
that sucks
Hey where can I learn python?
And how can I make discord bots by python??
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
https://discordpy.readthedocs.io/en/stable/quickstart.html
and link above for learning Python
wait than how do I learn about dblapi than?
Ok thx :)
Don't use it actually
if you ask in that server , they will for sure provide you some info about it
It's pretty bad
And doesn't do what you want anyways
yeah , making requests is better
oh
Official documentation for the discordbotlist.com API.
than how do I send a DM when my bot gets an upvote
already read it
Create an API
And use what's written in the vote-webhooks
Should ask in their server though
by api they actually meant creating a scenerio a.k.a a webserver their docs actually show how to get data of the voters
And that's why I recommend people to use top.gg and not this website xD
asked thats where tehy told me to use integromat and make a scenerio by making custom webhook and connect HTTP
which isnt working
can't my bot is nsfw top.gg doesnt take nsfw bots
yikes
you know about express-py?
Well you need an API either way
one of the site helpers told me to use express-py and than make a web server to make the bot send DM use replit for hosting purpose and install a listener
What kind of helper is that xD
idk man
I'm pretty sure Flask can do the job actually
by making a discord bot dashbaord?
No?
and than get data of voters and than make the bot DM?
It's not just for a dashboard
is there any doc?
how do i change channel permissions for everyone from default to locked
do you mean send_messages =False?
hmmm
can you tell me which topic to read first?
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
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...
oh ty
good luck bhai
for target, do i just put @everyone? or just everyone
huh
You want Guild.default_role which is the @everyone role
oh so i leave it blank or?
You can't just pass the name you need to pass the object
okay ty
wait, so in the docs it said if i did overwrite = None then it will delete the overwrite, does it delete the overwrite only for that specific perms in that role or all overwrites for the role? what if i wanna keep it as it was previously
It deletes the overwrites in that channel for a target
ohh okay ty
File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined
||token||
show code, define bot
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = ">")
@bot.event
async def on_ready():
print("Bot Online")
bot.run("Token)
hm
tell em whats wrong
it works fine for me
bot.run("Token) should be bot.run("Token") tho
I have used that only bot.run(token)
strange, the code is correct
what should i do?
can you get a FULL traceback please?
!traceback
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.
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS E:\Projects\Bot Development\Not decided> & C:/Users/user/AppData/Local/Programs/Python/Python39/python.exe
Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
bot.run("69696")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bot' is not defined
I hope that isn't your actual token
so i see it's opening the REPR
which can be seen from the >>>
meaning it's not actually running your file, but instead it's just doing the python REPR
and i guess it's inserting your code but not correctly
you want the command to be python file.py with file being your actual filename
it's now just doing python without the file
@bitter anchor
I din't understand @valid niche????
you're only running the python.exe
what you should be doing is python file.py
or python.exe file.py
with file.py being your actual bot file
by....running python file.py instead of python?
then?
go to the directory where ur bot.py or main.py or whateverucallit.py file is
ok
E:\Projects\Bot : The term 'E:\Projects\Bot' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
- E:\Projects\Bot Development\Not decided
-
+ CategoryInfo : ObjectNotFound: (E:\Projects\Bot:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
it's cd path/to/file
cd 'E:\Projects\Bot'
same error
share a screenshot
mate
u r already in the directory
# https://discord.com/api/v8/channels/885472410176991242/Messages
r = requests.post() ``` I’m stuck im trying to make discord bot to make @lament oar1 announcement
just run python main.py there, replacing main.py with ur file name
because there is no E:\Projects\Bot Development\Not Decided\E:\Projects\Bot
cd works relative from the file you are in already
You need to pass Authorization headers and then pass a dict to the json kwarg of post
but i sense a great lack of basic python knowledge if you don't even know how to properly run your python script
the dictionary should have a key, content which has the value of @everyone
The headers should look like ```py
{"Authorization": "Bot {token}"}
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Ok
should learn basic python first ig, tho it should work fine in vs code even if u just press the run button
Hey what's wring in this code?
Why it shows me error (I am learning py 😅)
the thing is they aren't pressing the run button, or have some super wonky setting for runt that first opens the REPR and then inserts every line of code, and it's completely broken
help with my prob
process.env is for js iirc
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3.10/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3.10/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3.10/library/intro.html#availability): most flavors of Unix, Windows.
hmmmmmmmmmmmmm i never use vs code for python anyway
i use vsc and the command it runs is VERY different
bot = commands.Bot(command_prefix = ">")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'commands' is not defined
huh? it uses the terminal just like you would do in command prompt
@slate swan hey now it shows os is not defined, what should I do?
import os
How??
you didn't read it
this is the command it normally runs
PS C:\Users\Sebastian Kuipers\Desktop\Tekxitbot> & 'C:\Program Files\Python310\python.exe' 'c:\Users\Sebastian Kuipers\.vscode\extensions\ms-python.python-2021.9.1246542782\pythonFiles\lib\python\debugpy\launcher' '49994' '--' 'c:\Users\Sebastian Kuipers\Desktop\Tekxitbot\pybot.py'
why not just python pybot.py
REPR? Shouldn't it be REPL
that's what a normal human does, but the run button runs it using absolute paths to ensure it actually works when the terminal isn't in the correct directory, and also runs a debugger so it can hook into the stack and help with debugging
nice
so you can see that the user here didn't use the actual run button
hmmmmmm
weird, that code works properly in my pc
that's because they are doing just python and not python file.py
so what should i do?
so it's first doing python which opens the REPR, then inserts only the last line of code
hi, i did ```py
import discord
from discord import permissions
from discord.ext import commands
from discord.ext.commands.errors import BotMissingPermissions
class Giveaways(commands.cog):
def init(self, bot):
self.client = bot
def setup(bot):
bot.add_cog(Giveaways(bot))
@slate swan show screenshot of how u r running ur file
I didn't rlly understood, pls can you say in more detail? Plss
either use the actual built in run button that works, or use the correct command
doing just python opens a REPR which doesn't work for you
you need to do python file.py
run python in terminal
do you know what are imports in python?
that self.client tho......
like you literally already have bot
python main.py run this command once in ur terminal
why use self.client which is against all naming conventions?
Nope
I am beginner, I just started it
ignore that
commands.Cog
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
PS E:\Projects\Bot Development\Not decided>
oh capitalise
yes sir
well , just read some article describing imports
its basically like importing some functions
bruh
u sure u have python installed
Ok thx :)
you are aware discord bots are very complex and it requires a good amount of basic knowledge right?
it's FAR from a beginner project
u will do just fine with knowledge little above beginner level
Yup its installed
added to PATH?
press windows + r, type cmd, run it, the type python, show the output
my every python file works fine but discord bot dosent
show output, like press enter or something, it would either give and error message or run python
it opens microsoft store
oh also i see a youtube page with a discord bot tutorial
i've yet to see a singular youtube video that is actually a good guide
main issue is, videos are passive learning, aka one of the worst kinds
ig it thinks its not installed and tries to open microsoft store to install it from there?
well , your file on which you are working , and the name of file you run differs
should it not?
i mean , you are trying to run the same file right?
that's what it does yes
if it's not installed/not on path it opens the microsoft store
which is kinda the bad way to install python
best way to figure out is to dig into program files and find the python.exe
just open the environment variable settings and check the path variable^
How do you actually solve this ?
Delete self, your params starts with ctx, then do it as you do normally
ok
https://cdn.discordapp.com/attachments/893587801596125195/895272141849788426/unknown.png
does anybody know why i can't install "git"
client = discord.client()
keywords = {"is new server"}
@client.event
async def on_message(message):
for j in range(10):
await message.channel.send("new server")
client.run(“token”)```
Anyone can see problem in 2nd line
discord.Client()
I wouldn't suggest using client though
Use discord.Bot()
Ty
how do i dm a user by username
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
run it with sudo permisssions
wot
how do i do it
same error
do what
by bot or by you?
by bot
use the thing earlier > then send the mesage
dunno if ur planning to make a command tho
run this
sudo mv /var/lib/dpkg/info/install-info.postinst /var/lib/dpkg/info/install-info.postinst.bad
hmm
then try install git
i am making a ban command and when a user gets ban using the command it should dm the user who got banned
dm u got banned
send the message then ban them
y
@commands.command()
async def ban(self,ctx, member: discord.Member, *, reason=None):
embed = discord.Embed(
description=f"You have been banned in reason:{reason}", color=0xFF0000)
await ctx.member.send(embed=embed)
await member.ban(reason=reason)
embed = discord.Embed(
description=f"Successfully banned {member}", color=0x3FFF00)
await ctx.send(embed=embed)```
u dont need context
yea
thx
description=f"Successfully banned {member}", color=0x3FFF00)
await ctx.send(embed=embed)```
this needs ctx tho
no?
it doesnt tho
uh
you already defined member so why ctx?
no
no?
this sends it in the chat
no to the user
then send it to the member??
i dont understand what u want i already told u how to do it
how can i get all of the default emojis?
for emoji in discord.emojis:
print(emoji)
?
ping me when responding please
i think this will show the time in ur timezone
import datetime
now = datetime.datetime.now()
local_now = now.astimezone()
local_tz = local_now.tzinfo
local_tzname = local_tz.tzname(local_now)
print(local_tzname)
Use pytz
i still need help btw
.join
!d discord.Guild.emojis
All emojis that the guild owns.
@slate swan
how does that help him?
no... i want the default emojis, not server emojis
oh
well u can count them
i think theres about 300-500 default emoji's
wdym by counting?
y do u wanna get the amount of emoji's tho
how is it helping me?
i need this for a command
i dont think u can list/show it though
i need to print them... i dont see how counting helps here
oh
are there any good discord.py developer here?? i want to ask how can i make a personal prefix system?? i tried to search for it but the result is server prefix, not personal one
I highly do not recommend doing that. It'll be too much data to save and load when the bot grows.
lol
ok thanks
if you have a good db you dont have to worry
I don't think even a shared mongo cluster would be able to take more than 100,000 dictionaries.
You can print them
sql dbs
and also caching exists
postgresql can handle 10s of thousand of queries persecond
ik, but how do i?
By using this:
https://unicode.org/Public/emoji/13.1/emoji-sequences.txt
Note that there will be 590 emojis
So it's pretty much useless to make it
Can someone explain what to do to fix /ping, it doesnt work (besides remove client.command i already did)
pass_context NotLikeThis
Nice emote aka BD
delete your client definition
and just use bot
Maybe look the difference between your two @
Suppose I am in Guild A, but I want to invoke a command in such a way that the ctx would act as if the command was invoked in Guild B. How to achieve so?
ctx.guild = guild2?
PROFESSIONAL PYTHON
....?
We won't need your irrelevant stuff here thanks
So all i have to do is remove client.command?
replace client.command with bot.command
@bot.command()
async def hello(ctx):
guild2 = bot.get_guild(id)
ctx.guild = guild2
prodigy
Uhhh, this channel is also for discussion related to Python Bot Making
!eval @bot.command()
async def hello(ctx):
guild2 = bot.get_guild(id)
ctx.guild = guild2
its a property dont think you can set it
Well, there's no discord.Guild.send() method, so let's change Guild A and Guild B with a channel in guild A and a channel in guild B.
!eval
async def hello(ctx):
guild2 = bot.get_guild(id)
ctx.guild = guild2
that function gets called in the source code probably
so bru
If you change the context's guild you still did not change the context's channel.
And the channel is where a message would be sent.
doesn't have to be send
but you can get the guild from the channel, so that's good too
Nonono. I mean, suppose I have a command named channel which doesn't accept any args, but I want to invoke it in such a way that it returns the channel from any other guild... How can I do this?
If i do that it will fix?
yes
If you want to get a channel then you can do bot.get_channel(id).
Bro... I don't know which channel is it and I want the channel name only
And I can get the channel only when I can get that context from another guild
And you shouldn't use / as prefix
As it interferes with slash commands
No....?
Yes
I mean, why would it
async def command(ctx):
ctx.guild = bot.get_guild(guild_b_id)
main_channel_name = ctx.channel.name
ctx.channel = discord.utils.get(ctx.guild.text_channels, name=main_channel_name)
await ctx.channel.send("...")
If you have a command with the same name as a slash command in the server it will priviledge the slash command
Bro. I DON'T know the channel name and that's what I WANT to know
Then magic is what you wanna do.
at last u understand
Hunter, go practice print statements. You need it. 
Yea, time to do print "Hi"
That's python2, hunter.

!e
print "Hello, world!"
@dapper cobalt :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | print "Hello, world!"
003 | ^
004 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello, world!")?
OMG
Only python2.
that's gonna be me
localdate = datetime.date.today()
objend = datetime.date(2021, 11, 13)```
how can i get number of days between these 2?
Sooo?
send() doesn't have an embeds attr, only embed.
so the answer is
no?
The correct way to print is... I'm not gonna spoonfeed ya.

embeds=[list of embeds]
