We are creating an Discord bot.
The Problem is that no error is in Console but the Chat in Discord is also empty. So no response at all. Could you please help me and say what my error is and how to resolve the problem
Best Wishes,
Niktix
import discord
from discord.ext import commands
import asyncio
from dotenv import load_dotenv
from discord.ext.commands import Bot
import askai
import numpy
import random
import json
import datetime as DT
from time import sleep
import sLOUT as lout
import os
botStartTime = DT.datetime.now()
ver = ['v1.0.8', '2021-01-13']
config = 'config.yml'
bot = commands.Bot(command_prefix = '!')
lout.writeFile('AskAIBotLogs.txt', '\naskai initialisiert!', True)
load_dotenv()
#bot.command(pass_context=True)
async def time(ctx):
startTime = DT.datetime.now()
await ctx.send('Auf dem server ist aktuell folgende Uhrzeit: {}'.format(DT.datetime.now()))
lout.log(config, startTime, 'time')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=1, name='Beantwortet Fragen', url='https://www.youtube.com/watch?v=e3tuUKGIaGw', platform='YouTube', assets='askai',))
lout.log(config, botStartTime, None, None, True)
print('Eingeloggt als {}'.format(bot.user.name))
#bot.event
async def on_message(message):
if message.author.bot:
return
if message.channel.name != "askai-support":
return
if message.content.startswith("!"):
return
await bot.process_commands(message)
await message.channel.send(askai.ask(message.content))
bot.run('token')
Why does it not work? Well, the answer is fairly simple. Please refer to the following lines you provided:
#bot.event
async def on_message(message):
if message.author.bot:
return
if message.channel.name != "askai-support":
return
At this point in the code, you provide the channel name. Although, you don't provide the channel ID afterward. Therefore the bot cannot get said channel. In order to get the channel ID, please refer to Discord's official guide here. Upon doing that, make the same line of code as above, although replace "message.channel.name" with "message.channel.ID". Let me know if you have any further questions. Best Regards,
Related
So, I have been working on a killswitch for my bot in discord.py, and I've hit a stump. My kill switch is not working and it's not giving me an error. If anyone can help I would very much appreciate it.
import discord
from discord.ext import commands, tasks
from keep_alive import keep_alive
import asyncio
import random
import json
import random
import discord.utils
from datetime import datetime
client = commands.Bot(command_prefix=',')
client.remove_command('help')
#client.event
async def on_ready():
global startdate
startdate = datetime.now()
await client.change_presence(
status=discord.Status.online,
activity=discord.Game('Type "," to activate me! e'))
print('Bot is ready.')
#client.command(aliases=["shut", "shutdown", "quit", "stop_that", "stahp", "kill"])
#commands.has_permissions(administrator=True)
async def stop(ctx, member: discord.Member = None):
embed = discord.Embed(colour=discord.Green())
embed.add_field(name="I have been Killed", value=f"{member.name} has killed me! That's very unpog of them!", inline=False)
embed.set_image(url="")
embed.set_thumbnail(url="")
embed.set_footer(text=f"Killed By: {ctx.author.name}")
await ctx.send(embed=embed)
await client.logout()
client.run('no token for you :)')
The first thing I saw in your code was when you defined the embed you only defined the color. I went ahead and added the other fields for title and description and set them to None
The second issue I saw was that when adding the field value, you called member.name
however you were supposed to call member.display_name
The final two issues are you were defining an embed image and thumbnail, however you did not pass any values. Instead, either pass None or do not define them in the first place
`
import discord
from discord.ext import commands, tasks
import asyncio
import random
import json
import random
import discord.utils
from datetime import datetime
client = commands.Bot(command_prefix=',')
client.remove_command('help')
#client.event
async def on_ready():
global startdate
startdate = datetime.now()
await client.change_presence(
status=discord.Status.online,
activity=discord.Game('Type "," to activate me! e'))
print('Bot is ready.')
#client.command(aliases=["shut", "shutdown", "quit", "stop_that", "stahp", "kill"])
#commands.has_permissions(administrator=True)
async def stop(ctx, member: discord.Member = None):
embed = discord.Embed(title=None, description=None, color=0x00FF00)
embed.add_field(name="I have been Killed", value=f"{member.display_name} has killed me! That's very unpog of them!", inline=False)
embed.set_footer(text=f"Killed By: {ctx.author.name}")
await ctx.send(embed=embed)
await client.logout()
client.run('YOUR TOKEN HERE')
`
I am trying to create a python script that would mute the users of a specific voice channel when executed. Till now I am able to mute everyone by typing the command in the discord text channel, but I would like to mute everyone when another python script tells the bot to. Below is my attempt to do that.
bot.py is the python discord bot:
import discord
from discord.ext import commands
from time import sleep
client = commands.Bot(command_prefix="./")
#client.event
async def on_ready():
print("Bot is online. ")
#client.command()
async def play_music_test():
channel = await client.get_channel(voice_channel_number)
voice = await channel.connect()
await voice.play(
discord.FFmpegPCMAudio(executable="C:/Users/USER/ffmpeg/bin/ffmpeg.exe",
source="C:/Users/USER/Desktop/song.mp3"))
client.run(TOKEN)
abc.py is the other python script trying to call a function:
from bot import play_music_test
import asyncio
print("")
asyncio.run(play_music_test())
I ran the bot.py first and then tried to execute the abc.py next, bot came online but when executing abc.py, it didn't print or do anything at all. I just started to learn discord.py so if this is a silly question, forgive me.
Instead of running the python file you can import it, or making it a cog
heres an example:
importing: bot.py
import discord
from discord.ext import commands
from time import sleep
from abc import *
client = commands.Bot(command_prefix="./")
#client.event
async def on_ready():
print("Bot is online. ")
#client.command(name = "play_music", aliases = ["you can asign aliases like this", "multiple ones too"])
async def play_music_test(ctx, channel): # If the python file doesn't know what channel is, it can be asigned when calling the function in discord, think of it like sys.argv or argparse
if channel == None: channel = ctx.channel # This sets the current channel you are in if none was provided when executing it in discord
# channel = await client.get_channel(channel) now you don't need this line
voice = await channel.connect()
await voice.play(
discord.FFmpegPCMAudio(executable="C:/Users/USER/ffmpeg/bin/ffmpeg.exe",
source="C:/Users/USER/Desktop/song.mp3"))
client.run(TOKEN)
importing: abc.py
remove asyncio.run(play_music_test())
use it in discord instead! ex. play_music_test #general
Making it a cog: bot.py
import discord
from discord.ext import commands
from time import sleep
import os
client = commands.Bot(command_prefix="./")
#client.event
async def on_ready():
print("Bot is online. ")
for filename in os.listdir("./"):
if filename == "bot.py": continue
else: client.load_extension(f"cogs.{filename[:-3]}")
client.run(TOKEN)
Making it a cog: abc.py
from bot import play_music_test
import asyncio
class Mycog(commands.Cog):
def __init__(self, client):
self.client = client
#client.command(name = "play_music", aliases = ["you can asign aliases like this",
"multiple ones too"])
async def play_music_test(ctx, channel): # If the python file doesn't know what
channel is, it can be asigned when calling the function in discord, think of it like sys.argv or argparse
if channel == None: channel = ctx.channel # This sets the current channel you are in if none was provided when executing it in discord
# channel = await client.get_channel(channel) now you don't need this line
voice = await channel.connect()
await voice.play(
discord.FFmpegPCMAudio(executable="C:/Users/USER/ffmpeg/bin/ffmpeg.exe",
source="C:/Users/USER/Desktop/song.mp3"))
def setup(client):
client.add_cog(Mycog(client))
This anwser is not the best but hope this helps!
i'm not sure, if i really understand, what you try to do, but to open a script from another script, i use subprocess.Popen()
but i think, in your case it fits more, to change the way you try to solve your problem. maybe you should take a look into the on_message event and use message.content
?
You can importing your client variable (from bot import play_music_test, client) and then client.loop.create_task(play_music_test())
(Although I do not understand why you would do such a thing)
I want to create a Python Bot which tracks the time a user has spent in voice state on a server to create a ranking system. Unfortunaley i dont know how to update the guild.members list and thus the member.voice value.
I tried doing a while loop but the list didnt seem to update.
Help would be greately appreciated.
# bot.py
import os
import asyncio
import discord
import random
import datetime
from discord.utils import get
import time
from dotenv import load_dotenv
from discord.ext import tasks
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
#client.event
async def on_ready():
print("Bot is ready")
while True:
time.sleep(2)
guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds)
for m in guild.members:
print(m.voice)
time.sleep(2)
client.run(TOKEN)
You can use the on_voice_state_update() event to keep track of every single member that connects / disconnect from a voice channel. Make sure to use the discord.ext.commands client object.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='$')
#client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel:
await start_tracking(member) #your method that tracks the time
#Remember that it has to be a coroutine
if before.channel and not after.channel:
await stop_tracking(member)
edit: please do not use time.sleep() in async scripts. use asyncio for stuff like sleeping and for loops
#client.event
async def on_message(message):
await client.process_commands(message)
I have no idea how to use this.
The above code is totally fine. If you haven't DEFINED Your bot yet, You have to do it.
Here is the simple code you can modify according to your needs.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = 'YOUR PREFIX')
#bot.command()
async def ling(ctx):
await ctx.send("Mabel")
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import time
bot = commands.Bot(command_prefix='$')
#bot.event
async def on_ready():
print ("Ready")
#bot.command(pass_context=True)
async def Move(ctx):
#channel to move to '414543063575429131'
#user to move '192361974053470208'
await bot.move_member('192361974053470208', '414543063575429131')
print("done")
bot.run("token_here")
This is my code but I when I try to move the user it gives me the error "The channel provided must be a voice channel."
I know the bot works because I had some simple commands earlier that would reply to messages earlier and they worked fine.
I am new to python and discord bots so I don't really know what to do. Any help is appreciated.
The channel argument to move_member must be a Channel object, not just the channel id. This is noted in the documentation for move_member
You cannot pass in a Object instead of a Channel object in this function.
#bot.command(pass_context=True)
async def move(ctx):
destination = '414543063575429131'
user = '192361974053470208'
await bot.move_member(ctx.message.server.get_member(user), bot.get_channel(destination))
# The get_member doesn't look to be strictly necessary, but it doesn't hurt
# and improves readability
print("done")