Discord.py User nickname changing - python-3.x

I have been trying to make myself a bot for my ArmA 3 unit, and upon doing so I have tried to create an Enlisting command, which changes the users existing Nickname within the server to the one that they enlist with (Their ArmA soldier name). But I am having some trouble figuring out how to do this. I'll leave my code down below for you to look at and hopefully figure out a solution :
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
Client = discord.Client()
client = commands.Bot(command_prefix = "+.")
#client.event
async def on_ready():
print("ToLate Special Operations Reporting For Duty")
await client.change_presence(game=discord.Game(name="By Slay > $enlist", type=3))
print("For more information: Please contact Slay on twitter #OverflowEIP")
#client.event
async def on_message(message):
if message.content.upper().startswith('+.ENLIST'):
client.change_nickname(message.content.replace('changeNick', ''))
client.run('token')

change_nickname is a coroutine, so you have to await it. You're also not really using commands properly. You should be defining separate coroutines for each command and decorating them with the client.command decorator. (You also don't need Client, commands.Bot is a subclass of discord.Client)
from discord.ext.commands import Bot
from discord.utils import get
client = commands.Bot(command_prefix = "+.")
#client.event
async def on_ready():
print("ToLate Special Operations Reporting For Duty")
await client.change_presence(game=discord.Game(name="By Slay > $enlist", type=3))
print("For more information: Please contact Slay on twitter #OverflowEIP")
#client.command(pass_context=True)
async def enlist(ctx, *, nickname):
await client.change_nickname(ctx.message.author, nickname)
role = get(ctx.message.server.roles, name='ARMA_ROLE') # Replace ARMA_ROLE as appropriate
if role: # If get could find the role
await client.add_role(ctx.message.author, role)
client.run('token')
enlist(ctx, *, nickname) means we accept commands like
+.enlist apple
+.enlist bag cat
+.enlist "dog eat"
and will assign those users (the person who called the command) the nicknames
apple
bag cat
"dog eat"

Related

Nextcord Ban & Kick issue

I'm trying to make a discord.py bot with the help of nextcord and i've come far enough to make the code work in theory but nothing happens when i try to kick / ban, it just throws an
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'ban'
and i have no idea why it does so, i want it to work as inteded.
Note, the command(s) are class commands so the main bot loads in the command from another file.
Main Bot Script
# import nextcord
from nextcord.ext import commands
# import asyncio
import json
# Import all of the commands
from cogs.ban import ban
from cogs.hello import hello
from cogs.help import help
from cogs.info import info
from cogs.kick import kick
from cogs.test import test
#Define bot prefix and also remove the help command built in.
bot = commands.Bot(command_prefix=json.load(open("config.json"))["prefix"])
bot.remove_command("help")
#bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
bot.add_cog(hello(bot))
bot.add_cog(help(bot))
bot.add_cog(info(bot))
bot.add_cog(test(bot))
bot.add_cog(ban(bot))
bot.add_cog(kick(bot))
bot.run(json.load(open("config.json"))["token"])
Problematic command
import discord
from nextcord.ext import commands
from nextcord.ext.commands import has_permissions, CheckFailure
bot = commands.bot
class ban(commands.Cog):
def __init__(self, client):
self.client = client
self._last_member = None
#commands.Cog.listener()
async def on_ready(self):
print('ban Cog Ready')
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: discord.Member = None, *, Reason = None):
if user == None:
await ctx.send("Could you please enter a valid user?")
return
try:
await user.ban(reason=Reason)
await ctx.send(f'**{0}** has been banned.'.format(str(user)))
except Exception as error:
if isinstance(error, CheckFailure):
await ctx.send("Looks like you don't have the permissions to use this command.")
else:
await ctx.send(error)
You are doing:
user: discord.Member
You need to use nextcord instead.
user: nextcord.Member
#commands.command()
#has_permissions(ban_members=True)
async def ban(ctx, user: nextcord.Member = None, *, Reason = None):#
#The rest of your code here
You can do the following
For Normal bot
#client.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
You can do the following
For Cogs
#commands.command(name="ban", aliases=["modbancmd"], description="Bans the mentioned user.")
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: nextcord.Member, *, reason=None):
# Code for embed (optional)
await member.ban(reason=reason)
# (optional) await ctx.send(embed=banembed)
Well, here are the problems:
Your command is in a cog therefore you need to say (self, ctx, and so on)
You need to change the discord to nextcord
You should change the commands.bot to commands.Bot()
And if I'm correct, you should change the self.client to self.bot since your commands.Bot() is defined as bot
And uhh yeah it should work perfectly after you fix those.

How do i make a discord bot receive text after a command

I want to become a fake discord bot, so i can use: !!send or something like that.
I have the token ready and i tried some repl.it templates but i have no idea of what to do.
here is the code i tried:
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
os.environ["TOKEN"] = "no-token-for-you-to-see-here"
#^ basic imports for other features of discord.py and python ^
client = discord.Client()
client = commands.Bot(command_prefix = '!!') #put your own prefix here
#client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
#client.command(pass_context=True)
async def send(ctx,*,message):
await client.say(message)
client.run(os.getenv("TOKEN")) #get your bot token and create a key named `TOKEN` to the secrets panel then paste your bot token as the value.
#to keep your bot from shutting down use https://uptimerobot.com then create a https:// monitor and put the link to the website that appewars when you run this repl in the monitor and it will keep your bot alive by pinging the flask server
#enjoy!
It was online, but the command didn't work.
The command send should be
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
Also, you're defining two client(s). You need only one.
client = commands.Bot(command_prefix = '!!')
You're also importing some useless modules that you don't need right now.
Your final code should look like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!!")
#client.event
async def on_ready():
print("The bot is online")
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
client.run("token-of-the-bot")
Please tell me if it works or not. Have a great day :)

discord.py send pm on member join

I'm trying to write a bot that sends a user a pm when he joins the server.
I searched and I found that to d this you need to have intents enabled, but when I enable them it gives me an error "RuntimeError: Event loop is closed". I can't figure out what exactly not working, I've seen somewhere that regenerate the bot token helps but it didn't help for me.
this is the code:
import discord
from discord.ext import commands
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member}"
await member.send(welcome_msg)
bot.run(TOKEN)
I see that you are trying to DM the user as soon as they join a server, you should did {member} and the argument "member" is just a guild version of The user, and to display the name with member.name there for it will show the Member's name on the message.
Here is your Fixed Code:
import discord
from discord.ext import commands, tasks # add tasks if you're going to do tasks.
from dotenv import load_dotenv
from pathlib import Path
import os
# Load token
env_path = os.path.join(Path('.'), '.env')
load_dotenv(dotenv_path=env_path)
TOKEN = os.environ.get('DISCORD_TOKEN')
intents = discord.Intents(members=True)
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print('Bot is running...')
print(f"Name: {bot.user.name}")
print(f"ID: {bot.user.id}")
print('------')
#bot.event
async def on_member_join(member):
welcome_msg = f"hi {member.name}" # You don't need to define the message.
await member.send(welcome_msg) # You can do await member.send("message") instead of defining it.
bot.run(TOKEN)
Hope this helped. Have a nice day!

Simplest way to check the users in channel with discord.py

I am making a simple bot, all I want it to do is wait for me to type a command with an argument (a vc), so for example when I type !channel general, the bot will return a list of the members in that channel. So if Bob and Jeff are in General the bot will return member_list = ['Bob', 'Jeff'] Any easy way to do that?
Update:
import discord
import os
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='$')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command()
async def members(ctx, channel: discord.VoiceChannel):
member_list = [i.name for i in channel.members]
print(member_list)
await ctx.send(member_list) # or return member_list whatever you want
client.run(os.getenv('TOKEN'))
Here's my code up above, when I run bot it does not do anything when I type $members general, anyone know what I'm doing wrong?
Use VoiceChannel.members
#bot.command()
async def members(ctx, channel: discord.VoiceChannel):
member_list = [i.name for i in channel.members]
await ctx.send(member_list) # or return member_list whatever you want

Simple bot command is not working in discord.py

I want to know in which text channels admin want to enable my bot functions. But in this case my code is not working.
The main idea was when admin typing !enable in text-chat, bot reacts to it and add text-chat id, guild id(ctx.channel.id) to the list, then bot responds in chat with bot has been enabled.
code where this command is not working:
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
full bot code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}.')
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
#bot.event
async def on_message(ctx):
if ctx.author == bot.user:
return
#if ctx.channel.id != [for channnels in channel]:
# return
if ctx.attachments[0].height:
await ctx.author.send('Your media file is restricted!')
await ctx.delete()
The channel variable is initialized in your program so each time you will restart your bot, it will be emptied. One way you can solve your problem is by storing them in a file. The easiest way to do it would be to use the json library. You'll need to create a channels.json file.
The code :
from json import loads, dumps
def get_data():
with open('channels.json', 'r') as file:
return loads(file.read())
def set_data(chan):
with open('channels.json', 'w') as file:
file.write(dumps(chan, indent=2))
#bot.command()
async def enable(ctx):
channels = get_data()
channels.append(ctx.channel.id)
set_data(channels)
await ctx.send('Restriction bot has been enabled for this text channel.')
The channels.json file :
[]

Resources