Discord.py Command Prefix Not Calling Out Commands? - discord.py

I've been trying to figure this out forever now, but it seems that my discord.py command prefix for my bot does not work. Currently, here is my code:
players = {}
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
await client.change_presence(activity=discord.Game(name="with your words!"))
called_once_an_hour.start()
#client.command()
async def test():
await client.send('test')
#client.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
#client.command(pass_context = True)
async def leave(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
await voice_client.disconnect()
#client.command(pass_context = True)
async def play(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=YMw-9mXfccY')
players[server.id] = player
player.start()
print(f"Playing Are you winning son in server voice client: {voice_client}")
First client command was mainly for debugging purposes, but its just never called out.
I also think I already have all the necessary imports

Your test command needs to look like:
async def test(ctx):
await ctx.send('test')
I can run this successfully with !test
The context is passed by default, pass_context = True is no longer necessary.
See the commands docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html

Related

Discord.py Bot wont start, getting error "Main.run' was never awaited" but i dont know why I should await it

class Main:
def __init__(self):
self.client = None
async def register_commands(self):
self.client.remove_command("help")
await self.client.add_cog(BlacklistCommand(self.client))
await self.client.add_cog(ClearCommand(self.client))
await self.client.add_cog(DoxCommand(self.client))
await self.client.add_cog(HelpCommand(self.client))
await self.client.add_cog(InfoCommand(self.client))
await self.client.add_cog(IpCommand(self.client))
await self.client.add_cog(SlayerCommand(self.client))
async def register_events(self):
await self.client.add_cog(CommandErrorListener(self.client))
await self.client.add_cog(OnMessageListener(self.client))
await self.client.add_cog(OnReadyListener(self.client))
async def run(self):
token = json.load(open('files/apikeys.json'))['discord']['bot_token']
intents = discord.Intents().all()
self.client = commands.Bot("ยง", intents=intents, case_insensitive=True)
await self.register_commands()
await self.register_events()
self.client.run(token)
Main().run()
I tried running it and it it just gave me an error message "
RuntimeWarning: coroutine 'Main.run' was never awaited
Main().run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Process finished with exit code 0"
but i dont know why I should await it
You should await it because you made the function async
async def run(self):
# ^^^^^ <- it's async, so it must be awaited
If you want to do any async setup, either make an async main or use the built-in setup_hook function.
The migration guide explains how to do both: https://discordpy.readthedocs.io/en/stable/migrating.html?highlight=setup_hook#asyncio-event-loop-changes

How do I DM a person with Discord.py??? Why won't my code work?

import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print('Running...')
#client.event
async def on_message(message):
while True:
user = client.get_user('user')
await user.send('hi')
I have tried a million variations of this and it won't work.
Why won't send work????????
I just tested this with the latest version of pycord and it works.
import discord
import os
import asyncio
TOKEN = "TOKEN_HERE"
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents, members = True, messages = True, message_content = True)
#client.event
async def on_ready():
print("Running...")
#client.event
async def on_message(message):
user_id = message.author.id
user = await client.fetch_user(user_id)
await user.send("HI")
client.run(TOKEN)
I don't know why you had a while loop in there, I don't think it was needed. I used client.fetch_user as the method for getting the member object and included the intents for messages and members otherwise the bot won't be able to read messages or access member objects. You will need to make sure you have the intents enabled in your developer account for this to work.

Discord.py echo command

So I am trying to make a discord.py echo/say command, but no response or errors are happening, if you know how to fix this please help me out!
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.message.author.id in [782258096210051102]:
await ctx.send(args)
await ctx.message.delete()
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)
It's not working because the ctx.author is None, to fix that enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(..., intents=intents)
Also make sure to enable them in the developer portal
Reference
Uhhhhhh it is better to do something like
#bot.command()
async def echo(ctx,*,arg):
#the star is required
if ctx.authir.id==782258096210051102:
await ctx.send(arg)
else:
await ctx.send("devs only :<")
You can use ' '.join(ctx.message.content.split()[1:]) to join all words after the first space. So something like:
#client.command()
async def echo(ctx, *args):
await ctx.send(' '.join(ctx.message.content.split()[1:]))
To See Where The Problem Is From First Try:
#client.command()
async def echo(ctx, *,args):
await ctx.send(args[0])
await ctx.message.delete()
Ok so actually you have need to do this:
#client.command(name='echo')
async def echo(ctx, *, what_bot_need_to_say: str):
if ctx.message.author.id == 782258096210051102:
await ctx.channel.purge(limit=1) # This delete an message in the channel
await ctx.send(what_bot_need_to_say) # This the echo
else:
await ctx.send("Bot developers only :<")
#bot.command()
async def say(ctx, *, msg):
await ctx.send(msg)
Just copy me it is the simplest and gives the correct format
import discord
from discord.ext import commands
bot = commands.Bot('?')
#bot.command()
async def repeat(ctx,*,repeat:str):
if ctx.author.id == 782258096210051102:
await ctx.send(f"{repeat}")
await ctx.message.delete()
return
else:
await ctx.send("Only devs")
return
#bot.event
async def on_ready():
print("bot online")
bot.run("YOUR_TOKEN_HERE")
try this:
import discord, os, keep_alive, asyncio, datetime, pytz, requests
from discord.ext import tasks, commands
client = commands.Bot(
command_prefix=':',
self_bot=True
)
async def on_ready():
client.remove_command('help')
await client.change_presence(status=discord.Status.online, activity=discord.Game("TEST"))
#client.command()
async def echo(ctx, *,args):
if ctx.author.id in [782258096210051102]:
await ctx.send(args)
# await ctx.message.delete() # i am not sure of delete you can add it if you want
else:
await ctx.send("Bot developers only :<")
keep_alive.keep_alive()
client.run(os.getenv("TOKEN"), bot=False)

How to make lockdown and unlock commands discord.py

Im trying to make a lockdown and unlock command using discord.py rewrite. I have the code but it doesn't work at all. Can someone help me?
#client.command()
#commands.has_permissions(manage_channels = True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#commands.has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
I found out the issue. The commands work on every other server except for the one I'm testing it on. It turns out that That server makes everyone admin as soon as they join.
Try this, to enable the necessary bot permissions:
#client.command()
#has_permissions(manage_channels=True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role,send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
this is my unlock command hope it helps you
you have to use overwrites TextChannel.set_permissions
#client.command()
async def unlock(ctx, role:Optional[Role], channel:Optional[TextChannel]):
role = role or ctx.guild.default_role
channel = channel or ctx.channel
async with ctx.typing():
if ctx.author.permissions_in(channel).manage_permissions:
await ctx.channel.purge(limit=1)
overwrite = channel.overwrites_for(role)
overwrite.send_messages = True
await channel.set_permissions(role, overwrite=overwrite)
unlock_embed = discord.Embed(
title= ("UNLOCKED"),
description= (f"**{channel.mention}** HAS BEEN UNLOCKED FOR **{role}**"),
colour=0x00FFF5,
)
unlock_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
unlock_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
unlock_embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.channel.send(embed=unlock_embed, delete_after=10)
print("unlock")
else:
error3_embed=discord.Embed(title="ERROR", description="YOU DONT HAVE PERMISSION", colour=0xff0000)
error3_embed.set_thumbnail(url='https://images.emojiterra.com/google/android-11/512px/274c.png')
error3_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
error3_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
await ctx.channel.send(embed=error3_embed, delete_after=10)

on_typing not responding to typing discord.py

I am attempting to have a bot recognise when a user is typing and if that user is me, it sends a message. I don't know if I'm using this wrong but I read the API and at still doesn't make sense to me. the bot is not responding to any typing that I do in the default chat of my discord test server. I tried simplifying it to make sure that it actually wasn't seeing my typing and it still doesn't work, any ideas. the code is below.
import discord
from discord.ext import commands
token = ('~my token~')
client = commands.Bot(command_prefix = '.')
client.case_insensitive = (True)
#client.event
async def on_ready():
print('Ready')
#client.event
async def on_member_join(user):
print(f'~Temp~ {user} joined the server.')
#client.event
async def on_guild_join(server):
print(f'~Temp~ {server} joined')
#client.event
async def on_typing(channel, user, when):
print('Ready')
'''
if user.id == id1:
await channel.send('1')
elif user.id == id2:
await channel.send('2')
else:
await channel.send('3')
'''
#client.event
async def on_message(message):
print('~Temp~ Message found')
client.run(token)
You need to enable intents in order to work
intents = discord.Intents.default()
client = commands.Bot(.., intents=intents)
A Primer to Gateway Intents

Resources