Python - stops job on discord - python

The plan for this bot is to wake up --> retrieve data I need --> terminate itself.
I've tried using client.logout() and client.close(), but the program won't stop after it runs. Any advice?
import discord
import os
from discord.ext import tasks
from discord.ext import commands
discord_client = discord.Client()
#discord_client.event
async def on_ready():
for guild in discord_client.guilds:
if guild.name == GUILD:
break
print(
f'{discord_client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
# Send message when Bot wakes up
channel = discord_client.get_channel(ID)
await channel.send("*wakes up and starts working*")
retrieve_data.start()
await discord_client.logout()
#tasks.loop(count=1)
async def retrieve_data():
# do things here
discord_client.run(TOKEN)

You don't have your token defined, import load_dotenv and call it, you have undefined variables, also logout() is deprecated so use close() instead and it works.
import discord
import os
from discord.ext import tasks
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
discord_client = discord.Client()
#discord_client.event
async def on_ready():
# for guild in discord_client.guilds:
# if guild.name == GUILD:
# break
# print(
# f'{discord_client.user} is connected to the following guild:\n'
# f'{guild.name}(id: {guild.id})'
# )
# Send message when Bot wakes up
# channel = discord_client.get_channel(ID)
# await channel.send("*wakes up and starts working*")
await retrieve_data.start()
await discord_client.close()
#tasks.loop(count=1)
async def retrieve_data():
print("test")
discord_client.run(os.getenv("TOKEN"))

Related

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.

I want my bot to process commands sent by other bots

This isn't something most people want, but I do.
Code:
#imports
import discord
import os
from keep_alive import keep_alive
from discord.ext.commands import has_permissions, MissingPermissions
from discord.ext import commands
from discord.utils import get
#client name
client = discord.Client()
#log-in msg
#client.event
async def on_ready():
print("Successfully logged in as")
print(client.user)
#prefix and remove default help cmd
client = commands.Bot(command_prefix='H')
client.remove_command("help")
#client.command(pass_context=True)
async def ere(ctx, *, args=None):
await ctx.send("hi")
if discord.utils.get(ctx.message.author.roles, name="MEE6") != None:
if args != None:
await ctx.send("mee6 just spoke!")
else:
await ctx.send("nope")
#client.event
async def on_message(message):
print(message.author)
if "Here" in message.content:
if discord.utils.get(message.author.roles, name="MEE6") != None:
channel = await client.fetch_channel(870023245892575282)
await channel.send("yes")
await client.process_commands(message)
I figured adding "await client.process_commands(message)" to the bottom of on_message would process commands sent by other bots such as MEE6 but no luck. It appears by default on_message can hear bots but commands can not. Any way to get around this?
Any help would be greatly appreciated!
It is a feature of the Bot class to ignore other bot's messages, but #Daniel O'Brien solved it in this thread. The solution is to subclass the bot and override the function which ignores other bots, like this:
class UnfilteredBot(commands.Bot):
"""An overridden version of the Bot class that will listen to other bots."""
async def process_commands(self, message):
"""Override process_commands to listen to bots."""
ctx = await self.get_context(message)
await self.invoke(ctx)
Use ID
for commands:
# from discord.ext import commands as cmds
def is_mee6():
def predicate(ctx: cmds.Context):
return ctx.message.author.id == 159985870458322944:
# 159985870458322944 is ID of MEE6
return cmds.check(predicate)
# Use like it:
# #cmds.command()
# #is_mee6()
# async def ...
for events:
# from discord.ext import commands as cmds
mee6_id = 159985870458322944
# and use it for checks. for Example
#cmds.event
async def on_message(message):
if message.author.id == mee6_id:
# ANY

Not recognizing commands in discord with Python

I run this, it connects however when running it will not return anything when it comes to commands. I've tried changing this to the context return method from on every message. Previously only one message would appear, now none with this method even though both commands are the same with slight differences. What is my error on this? Sorry this is literally my first attempt at a discord bot.
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
discClient = discord.Client()
bot = commands.Bot(command_prefix = "!")
#discClient.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
discClient.run(botToken)
You heading in the right direction commands.Bot have both event and command no need to use a client just for events.
You should either use discord.Client or commands.Bot not both in your case it is commands.Bot.
Also you are running the client only
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
bot.run(botToken)

Python discord bots

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.

Updating the guild.members in discord.py Python

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

Categories

Resources