Python discord bots - python

I am currently trying to create my discord bot. sadly, this does not work and I have no Idea why...
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
there are NO errors. But no output aswell. I try making it join my vc by writing: .join

channel returns None, because ctx.message.author don't have voice attribute. Also, Client.join_voice_channel is deprecated since v1.0 (read here)
Instead of that, try this:
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.guild.get_member(ctx.author.id).voice.channel # This
await channel.connect()
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))

Do client.add_command(join). You currently have the function for your command, but you haven't told the bot to recognize it as a command.

Related

Why can't my discord.py bot see messages?

I am making a discord.py bot and it does not "see" messages at all, it is supposed to print everything into the terminal and have a prefix, but it doesn't even print any message.
code:
import datetime
import os
import discord
from timeit import default_timer as timer
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
bot = commands.Bot(command_prefix="!")
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
TOKEN = ('boop')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
async def on_message(message):
print(f'USER - {message.author} texted - {message.content}')
#bot.command()
async def start(ctx):
await ctx.channel.send("you have started")
await ctx.guild.create_role(name= {message.author} + "w")
client.run(TOKEN)
(there are extra unused modules I'm planning to use later)
There are a few problems in your code:
You should only have one commands.Bot instance, events are not exclusive to discord.Client.
For your bot to catch commands, you need bot.process_commands at the end of your on_message event.
You were missing #bot.event above on_message.
You forgot the fstring in ctx.guild.create_role(...).
import discord
from discord.ext import commands
import os
import datetime
from dotenv import load_dotenv
from timeit import default_timer as timer
load_dotenv()
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#bot.event
async def on_message(message):
print(f'USER - {message.author} texted - {message.content}')
await bot.process_commands(message)
#bot.command()
async def start(ctx):
await ctx.channel.send("You have started")
await ctx.guild.create_role(name=f"{message.author}w")
bot.run("TOKEN")

discord bot sends infinite messages regardless of user input

I'm trying to make a discord bot respond when someone makes laughing remarks but it infinitely sends gifs whenever someone types anything
code is as follows
import os
import discord
import random
from discord.ext import commands
import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
#bot.event
async def on_ready():
guild_count = 0
for guild in bot.guilds:
print(f"- {guild.id} (name: {guild.name})")
guild_count = guild_count + 1
print("AGOP_Bot is in " + str(guild_count) + " guilds.")
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content == "Lmao" or "Lol" or "lmao" or "lol" and message.author.id != bot_id:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
keep_alive.py
import os
import discord
import random
from discord.ext import commands
# import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
...
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content in ("Lmao" or "Lol" or "lmao" or "lol") and message.author.id != bot.user:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
# keep_alive.py
In addition to some formatting, I changed some of the variables for the API calls. I commented out the keep_alive.py as I assume you are using that to keep your code hosted on Repl.it or something, and you can just comment it back in. I was also able to get this code to work with my bot and execute as you want.

Why can't my main code run a custom module properly on Replit?

I have this code in a module for my discord bot to join a vc:
import discord
import ffmpeg
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
async def join(cxt):
vc = ctx.message.author.voice_channel
await client.join_voice_channel(channel)
But the main code doesn't run it and whenever I try my !join command it doesn't work. The bot still goes online, it just won't go on a voice channel. The module is commands. Please help!!
Main code:
import discord
import os
import requests
import json
import random
import youtube_dl
import commands
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
message.content = message.content.lower()
if message.author == client.user:
return
client.run(os.getenv('TOKEN'))
voice_channel is not an attribute of Member, which is the type of ctx.message.author. Instead, you want to look for a VoiceState in Member.voice:
async def join(ctx):
vc = ctx.message.author.voice.channel
if vc:
await vc.connect()
else:
# user isn't in voice
Similarly, you can't connect to a voice channel with Bot.join_voice_channel. You need to call connect() on the VoiceChannel or StageChannel object (if it exists, which is why you should check to see if Member.voice.channel is None.

Discord.py Why will this client.command not work?

import discord
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix="-")
#client.event
async def on_message(message):
if message.content.startswith("uno regeln"):
await message.channel.send('http://www.uno-kartenspiel.de/spielregeln/')
#client.command()
async def test(ctx):
await ctx.send("Ok")
client.run("TOKEN")
When I try to run this and use -test nothing happens
But why?
I looked in the docs but in my opinion everything is fine
As given by the link provided by #Lukasz KwieciƄski,
you need to change it to:
import discord
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix="-")
#client.event
async def on_message(message):
if message.content.startswith("uno regeln"):
await message.channel.send('http://www.uno-kartenspiel.de/spielregeln/')
await bot.process_commands(message)
#client.command()
async def test(ctx):
await ctx.send("Ok")
client.run("TOKEN")
import discord
from discord.ext import commands
intents = discord.Intents.default()
client = commands.Bot(command_prefix="!", intents=intents)
client.remove_command('help')
#client.event
async def on_ready():
print("Bot Is Ready")
await client.change_presence(activity=discord.Game(name="TYPE THERE ANYONE"))
#client.command()
async def test(ctx):
await ctx.send("Ok")
client.run('YOUR TOKEN')
Try this

Discord py not recognizing command

client.event works fine, connection and messages are registered. But cannot get discord to recognize command when I type i.e. '.ping'
python 3.7 on anaconda distribution
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv('.env.txt')
TOKEN = os.getenv('DISCORD_TOKEN')
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#client.event
async def on_message(message):
print(f'{client.user} has sent a message')
#client.command()
async def ping(ctx):
print('test')
await ctx.send('test')
client.run(TOKEN)
Alright, you need to understand that overridng the default on_message forbids any extra commands from running.
An easy fix for this, is to add a client.process_commands(message) to the end of the on_message event.
So in your case:
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv('.env.txt')
TOKEN = os.getenv('DISCORD_TOKEN')
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#client.event
async def on_message(message):
print(f'{client.user} has sent a message')
client.process_commands(message)
#client.command()
async def ping(ctx):
print('test')
await ctx.send('test')
client.run(TOKEN)```

Categories

Resources