I want to add a username or id to the code so that when I (or somebody else) does .d #username, the selfbot does the whole ".accept" and "u 4" response.
Code:
import discord
import os
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
client = discord.Client()
b = Bot(command_prefix = ".d")
#b.event
async def on_ready():
print("rdy")
#b.event
async def on_message(message)
if message.content == ".d":
await message.channel.send(".accept")
await message.channel.send("u 4")
b.run(os.getenv("TOKEN"), bot = False)
You should use commands it makes things alot easier.
#b.command(aliases=['.d'])
async def d(ctx, member: discord.Member):
await ctx.send(".accept")
await ctx.send("u 4")
I added the .d in aliases cause you cannot have a function starting with . . Here is the link for more information. https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=group#commands
Related
I want to receive information from the user from discord, but I don't know what to do.
I want to make a class to input data
if user write !make [name] [data], bot generate class A, A(name, data)
The following is the code I made. What should I do?
Ps. command_prefix is not working properly. What should I do with this?
`
import discord, asyncio
import char # class file
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("Game"))
#client.event
async def on_message(message):
if message.content == "test":
await message.channel.send ("{} | {}, Hello".format(message.author, message.author.mention))
await message.author.send ("{} | {}, User, Hello".format(message.author, message.author.mention))
if message.content =="!help":
await message.channel.send ("hello, I'm bot 0.0.1 Alpha")
async def new_class(ctx,user:discord.user,context1,context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.message.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
client.run('-')
`
I advice to not using on message for making commands
what I do advice:
import discord
from discord.ext import commands
#bot.command(name="name here if you want a different one than the function name", description="describe it here", hidden=False) #set hidden to True to hide it in the help
async def mycommand(ctx, argument1, argument2):
'''A longer description of the command
Usage example:
!mycommand hi 1
'''
await ctx.send(f"Got {argument1} and {argument2}")
if you will use the two ways together then add after this line
await message.channel.send ("hello, I'm bot 0.0.1 Alpha")
this:
else:
await bot.process_commands(message)
if you want to make help command u should first remove the default one
by editing this line bot = commands.Bot(command_prefix='!',intents=intents) to :
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
overall code should look like
import discord, asyncio
import char # class file
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("Game"))
#client.event
async def on_message(message):
async def new_class(ctx,user:discord.user,context1,context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.message.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
#bot.command()
async def make(ctx,name,data):
#do whatever u want with the name and data premeter
pass
#bot.command()
async def help(ctx):
await ctx.send("hello, I'm bot 0.0.1 Alpha")
#bot.command()
async def test(ctx):
await ctx.send ("{} | {}, Hello".format(ctx.author, ctx.author.mention))
client.run('-')
and yeah if u want to know what is ctx
ctx is context which is default premeter and have some methods like send,author and more
Not sure that I need to use the both runs at the same time, but:
from multiprocessing.dummy.connection import Client
from telnetlib import DM
from typing_extensions import Required
import discord
from discord.utils import get
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType
from dislash.interactions import *
client = discord.Client()
from message import *
#client.event
async def on_message(message):
if message.author == client.user:
return
User_id = message.author.id
if message.channel.id == 1009530463108476968:
NewMessage = message.content.split(' ', 1)[0]
LimitLenght = len(NewMessage) + 11
if len(message.clean_content) >= LimitLenght:
await message.delete()
await message.author.send("Hello, " + f"<#{User_id}>" + "\nPlease, don't send any messages that break the **Counting-game** rules!\nIt's forbidden to post a comment that is longer than 10 characters.")
# More code
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot)
#inter_client.slash_command(name="help", description="Shows the help-menu")
async def help(ctx):
embedVar = discord.Embed(title="Test project", description="*The blue text is clickable.*\n⠀", color=0x0000ff)
embedVar.add_field(name="Rules", value='To see rules write **/Rules**\n⠀', inline=False)
await ctx.reply(embed=embedVar, delete_after=180)
bot.run('ToKeN')
client.run('ToKeN')
If you run this code and comment the "bot.run('ToKeN')", the first part of the code will work (def on_message), however the command '/help' will not work. If you change it (comment 'client.run('ToKeN')'), the command '/help' will work, but def on_message not.
What are the possible solutions? Thanks.
The .runs block each other and prevent from running. You shouldn't be using a client and a bot anyway. Use one commands.Bot instead. It subclasses a Client and it should be able to do everything you can do with the client.
bot = commands.Bot(command_prefix="!")
inter_client = InteractionClient(bot)
#bot.event
async def on_message(message):
...
#inter_client.slash_command(name="help", description="Shows the help-menu")
async def help(ctx):
...
bot.run(token)
I've just started learn python and my discord bot won't go online. it just said
" Process exit with exit code 0". And there's no error with the code.
here's my code. enter image description here
Add await client.process_commands(ctx) and #client.event don't need parentheses(). Use the code given below:
#client.event
async def on_message(ctx):
if ctx.author == client.user:
return
await client.process_commands(ctx)
Use this entire code if it still not working:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(command_prefix="s!")
#bot.event
async def on_ready():
print("running")
bot.run(discord_token)
#bot.command()
async def on_ready():
print("running")
bot.run(discord_token)
and the output should be running
You should try this instead
import os
import discord
from discord.ext import commands
discord_token = "Your Token"
client = discord.Client()
bot = commands.Bot(client_prefix="!")
#client.command()
async def on_ready():
print("running")
bot.run(discord_token)
The code you gave is wrong, this is correct:
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!") # you don't need an extra discord.client Bot is enough
token = os.getenv("TOKEN")
#you should not run the program here you should run it at last
#bot.event #no need for brackets
async def on_ready():
print("running")
#bot.event
async def on_message(ctx):
if ctx.author == client.user:
return
#bot.command(name="span",description="YOUR DESCRIPTION HERE") # it is command and not commands
async def span_(ctx,amount:int,*,message):
for i in range(amount):
await ctx.send(message)
bot.run(token) #you should run the bot now only and this will work perfectly!
You can find the the documentation for discord.py here.
How can I send a message every x time with a discord bot with discord.py?
Here is my code:
import discord
from discord.ext import commands
from discord.ext import tasks
import os
TOKEN = 'xxxxxxxxxxx'
bot = commands.Bot(command_prefix='!',help_command=None,activity=discord.Game(name="!help"))
#tasks.loop(seconds=5)
async def ping(channel):
print("is the function being called")
channel = bot.get_channel(877115461014282320)
await channel.send('embed=embed')
bot.run(TOKEN)
Edit: I know I shouldn't leak my key but I edited it after 10 seconds and removed a letter why could someone still access it?
You have to start task using ping.start() in event on_ready or in some command.
import discord
from discord.ext import commands
from discord.ext import tasks
import os
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='!', help_command=None, activity=discord.Game(name="!help"))
#tasks.loop(seconds=5)
async def ping():
print("is the function being called")
#channel = bot.get_channel(877115461014282320)
#await channel.send('embed=embed')
#bot.event
async def on_ready():
print('on ready')
ping.start()
bot.run(TOKEN)
You have also ping.stop(), ping.cancel(), etc. See doc: tasks
I recently just tried to clean up my main.py file because there is lots of code in it. I wanted to store every command into a file. I started with the clear/purge command. Whenever i type >clean, i get the error, "command not found". How do i fix this? Code for some of the main.py and clear.py is below. Any help would be appreciated! :D
MAIN.PY
import discord
from discord import User
import os
from keep_alive import keep_alive
from discord.ext import commands
import random
import requests
import json
import asyncio
from discord.ext.commands import MissingPermissions
from discord.ext.commands import Bot, Greedy
from discord.ext.commands import CommandNotFound
bot=commands.Bot(command_prefix = '>')
bot.remove_command("help")
#bot.event
async def on_ready():
print('The bot is online')
await bot.change_presence(activity=discord.Game('>help | Bot made by ColeTMK'))
CLEAR.PY
from discord.ext import commands
import asyncio
from discord.ext.commands import MissingPermissions
bot=commands.Bot(command_prefix = '>')
class Clear():
def __init__(self, bot):
self.bot = bot
#bot.command()
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount+1)
embed=discord.Embed(title="Clear Messages", description=f'{amount} messages were deleted!', color=0x00FFFF)
await ctx.send(embed=embed)
await asyncio.sleep(3)
await ctx.channel.purge(limit=1)
#clear.error
async def clear_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send(f"{ctx.author.mention}, Sorry, you do not have permission to do that!")
def setup(bot):
bot.add_cog(Clear(bot))
EDIT: better solution using COGS
Actually discord.py allows "cogs", see documentation here: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
here is an example too: https://gist.github.com/leovoel/46cd89ed6a8f41fd09c5