I am trying to make a bot with a simple function of creating a channel, but it is unsuccessful.
Here's my code:
import os
import discord
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='$',intents=intents)
guild = discord.Guild
#client.event
async def on_ready():
print("I'm in as " + str(client.user))
#bot.command(name = "hack")
async def court_create(ctx, msg):
print("Received: $hack") #output to console
channel_name = "hack-" + str(msg)
await ctx.send(channel_name) #output to channel
channel = await guild.create_text_channel(name = channel_name)
keep_alive()
Token = os.environ['Token']
client.run(Token)
Note that for debugging, I added two lines so that when it receives the command, it prints out to both the console and the channel. However, when I typed $hack 123 into the channel, it did nothing, not even outputting Received: $hack. Any ideas about this?
Bot has manage channel permission.
#bot.command(name = "hack")
async def court_create(ctx, msg):
The name in bot.command and the name of the function are two completely different names. It only reads what the function name is. If you want to add hack as another method of using the command you can use the aliases argument in bot.command()
Example:
#bot.command(aliases=["hack"])
async def court_create(ctx, msg):
Related
This is my full code. I'm using Replit to create a Discord bot.
import os
import discord
from keep_alive import keep_alive
# from discord.ext import commands
client = discord.Client()
global channelSaved
channelSaved = "default"
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
global channelSaved
if message.content.__contains__("!!reverse_"):
revmsg = message.content.replace("!!reverse_", "")
await message.channel.send(revmsg[::-1])
if message.content.__contains__("!!saychannel_"):
channelSaved = message.content.replace("!!saychannel_", "")
if message.content.__contains__("!!say_"):
saymsg = message.content.replace("!!say_", "")
await message.channel.send(saymsg)
print(channelSaved)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
Basically, I want to make it so that if you DM the bot with "!!saychannel_1234567890", with "1234567890" being the channel ID, it will save the channel ID to the channelSaved variable. Then if you say "!!say_Hello world", it will say "Hello world" in the channel specified by the channelSaved variable. I don't really know how to do this though. I'm mostly having trouble with getting the bot to say something in another Discord channel that isn't where it got the command.
I tried replacing the message.channel.send() in the "!!say" command with message.channelSaved.send() but it didn't work. It just gave me an error saying that 'Message' object has no attribute 'channelSaved'.
And by the way, if there's a better way to write these commands, please let me know!
You need to get the channel object from the client first and send the message to that channel
import discord
from keep_alive import keep_alive
# from discord.ext import commands
client = discord.Client()
global channelSaved
channelSaved = "default"
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
global channelSaved
if message.content.__contains__("!!reverse_"):
revmsg = message.content.replace("!!reverse_", "")
await message.channel.send(revmsg[::-1])
if message.content.__contains__("!!saychannel_"):
channelSaved = message.content.replace("!!saychannel_", "")
if message.content.__contains__("!!say_"):
saymsg = message.content.replace("!!say_", "")
chan = client.get_channel(channelSaved)
if chan:
await chan.send(saymsg)
print(channelSaved)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
My console dont show any errors, the slash commands works, but when I type "!dog", it should return "dog", but nothing happen.
'''
import discord
import random
from discord import app_commands
from discord.ext import commands
id_do_servidor = my_server_id
class client(discord.Client):
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all())
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(
guild=discord.Object(id=id_do_servidor)
)
self.synced = True
print(f"{self.user.name} is online.")
aclient = client()
tree = app_commands.CommandTree(aclient)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.command(name='dog')
async def sapo(ctx):
await ctx.send('dog')
#tree.command(guild=discord.Object(id=id_do_servidor),
name='test',
description='test')
async def slash2(interaction: discord.Interaction):
await interaction.response.send_message(f"Working!",
ephemeral=True)
aclient.run(
'my_bot_token')
'''
If someone know a solution, please help me, thanks for your atention.
You have both a discord client (aclient), and the bot object (bot), in your code, but you only run the bot on aclient (and the commands are registered to the bot object, so hence do not work). You cannot use both a client and bot object at the same time. In your instance, change class client(discord.Client): to class client(commands.Bot): and change the constructor to have the parameters you've used with the bot: super().__init__((command_prefix="!", intents=discord.Intents.default())
Then, simply replace any more references in your code using bot to aclient, ie:
#bot.command(name='dog') -> #aclient.command(name='dog')
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 am trying to "#" specific members after issuing a command, the following doesn't seem to work.
from tokens.token import discord_token
from discord.ext import commands
from discord.utils import get
intents = discord.Intents(messages=True, guilds=True)
client = commands.Bot(command_prefix="!",intents = intents)
#client.event
async def on_ready():
print("Bot is ready!")
#client.command
async def play(ctx):
paul = get(ctx.guild.members, name = 'paul')
john = get(ctx.guild.members, name = 'john')
await ctx.send("f{paul.mention} {john.mention} lets play games!")
client.run(discord_token)
It should return something like
MyBotName: #john #paul lets play games!
Thanks!
You have used f-string wrong in your code. f must be come before the string:
await ctx.send(f"{paul.mention} {john.mention} lets play games!")✅
await ctx.send("f{paul.mention} {john.mention} lets play games!")❌
Also if you didn't enable intents, go to the developer portal and enable intents. Then add it to your bot's properties with:
bot = commands.Bot(command_prefix="!", discord.Intents.all()) # or what you need
Hello guys im trying to write a code that gives me the discord server owner but its giving Me 'None'
import discord
client = discord.Client()
TOKEN = 'token'
#client.event
async def on_message(message):
if message.content.find("getowner") != -1:
await message.channel.send(str(message.guild.owner))
client.run(TOKEN)
Can someone please help me with this bot thanks!!
I want to get the discord servers owner by typing getowner in a text channel.
I recommend using it as a command rather than doing on_message, you can do this:
from discord.ext import commands
token = "Token"
client = commands.Bot(command_prefix="!") #Use any prefix
#client.command(pass_context=True)
async def getOwner(ctx):
#await ctx.channel.send(str(ctx.guild.owner.display_name))
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
But if you don't want to use a command, you could use regular expression and just keep it as:
import discord
import re
client = discord.Client()
TOKEN = 'token'
#client.event
async def on_message(ctx):
if re.match("getowner", ctx.content):
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
EDIT: Also try using intents with your bot code.
import discord
import re
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
TOKEN = "token"
#client.event
async def on_message(ctx):
if re.match("getowner", ctx.content):
await ctx.channel.send(str(ctx.guild.owner))
client.run(TOKEN)
Same changes can be done with the command version.
It's very simple;
from discord.ext import commands
#client.command(name="getowner")
async def getowner(ctx):
await ctx.send(str(ctx.guild.owner))