I want to stop the Discord Bot from running - python

So basically I'm doing something with a discord bot, and I got stuck in this.
let's say this is callBot_and_sendmessage function
def callBot_and_sendmessage(message):
#wake the bot
#client.event
async def on_ready():
await client.change_presence(activity = discord.Game(name='Do !help'))
#send the message
#client.event
async def on_message(message):
channel = client.get_channel(channelId)
await channel.send(message)
and my code is like this
message = input('Type a message: ')
callBot_and_sendmessage(message)
saveMessage(message)
the function saveMessage
def saveMessage(message):
with open(file, 'w') as fileData:
fileData.write(message)
My program won't call the saveMessage Function
so I need a way to stop the callBot_and_sendmessage aka the bot from running after sending the message
Can anyone help me with that ?

You can make the bot log out by using client.close(). Alternatively you can put exit(0) at the end (after the channel.send), so the script stops running after the message has been sent.

Related

Discord bot command from one bot to another

Hello guys I have simple discord bot on server and have a music bot. My simple bot just open txt file with links on music and send command in chat m!play link. But music bot doesn't see commands which are sent by my bot.
Music bot Jockie music
import discord
from random import randint
from conf import TOKEN
class DSClient(discord.Client):
async def on_ready(self):
print(self.guilds)
async def on_message(self, message):
if message.content == "Грязюка":
with open("songs.txt", "rt") as f:
tracks = [song.strip().split() for song in f.readlines()]
for _ in range(len(tracks)):
index = randint(0, len(tracks) - 1)
track = tracks.pop(index)
print(track)
await message.channel.send(f"m!play {track[0]}")
client = DSClient(intents=discord.Intents.default().all())
client.run(TOKEN)
my code
if the bot you want to give commands is not from you you can't fix this ... because they set it in their code so that is will only respond to user accounts.
If the Bot you want to give the command (music bot) is from you, you need to go to the code and make the command triggered by an on_message event, because the build in command handler from discord.py will only listen to user messages and ignore commands send by other bots
#bot.listen
async def on_message(message):
if message.content.startswith('m!play'):
await play_song(song_name=message.content.split(' ')[1])
the play_song function is here the async function that will play the song and I just passed here an example parameter.

Pycord bot not responding to commands

I have a discord bot with automod and XP system. I have made discord bots before so I know how to make a command, but now it does not seem to work and I don't know why.
When I say a curse it deletes my message and everything there works fine so the on_message works, but those commands don't work. It does not give any error when I type a command, but the but doesn't respond.
Any help would be appreciated.
Here is my code:
import discord
from discord.ext import commands
# Set up the client and command prefix
intents = discord.Intents.all() # Enable all intents
client = commands.Bot(prefix='$', intents=intents)
#client.event
async def on_ready():
print('Bot ready')
#client.command()
async def ping(ctx):
print("ping")
await ctx.send('pong')
#client.event
async def on_message(message):
# Ignore messages sent by the bot
if message.author == client.user:
return
# Do some XP things
...
# AutoMod things
...
# Process any commands that are sent by the user
await client.process_commands(message)
print("processing commands")
#client.command()
async def leaderboard(ctx):
# do something
...
# Start the bot
client.run('TOKEN')
Also all intents are enabled in discord developer portal
So what I expected to happen is the program would first print Bot ready. Then I would write $ping to discord and the program would print processing commands and then print pong and say pong in discord.
What actually happened is that the program Printed Bot ready. Then I wrote $ping, the program prints processing commands. And then nothing else happens

How to stop repetitive messages, and the token is changed, but it doesn't run

I started learning python today and made a Discord bot. I have a few problems:
If message.author == was used in the on_message, but the bot continued to reply to itself.
Afterwards, a new bot was created with a new token and the code didn't work.
I searched a lot on this site and Google. I didn't find any solution. It's okay to modify my code. Everything is from the internet, so it can be a mess. Please help me.
import discord
import asyncio
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('Loggend in Bot: ', bot.user.name)
print('Bot id: ', bot.user.id)
print('connection was succesful!')
print('=' * 30)
#client.event
async def on_message(message) :
if on_message.content.startswith('!의뢰'):
msg = on_message.channel.content[3:]
embed = discord.Embed(title = "브리핑", description = msg, color = 0x62c1cc)
embed.set_thumbnail(url="https://i.imgur.com/UDJYlV3.png")
embed.set_footer(text="C0de")
await on_message.channel.send("새로운 의뢰가 들어왔습니다", embed=embed)
await client.process_commands(message)
client.run("My bot's token.")
Your code was messy, but it should work now. I included comments to let you know how everything works. I think the good starting point to making your own bot is reading documentation. Especially Quickstart that shows you a simple example with explanation.
Write !example or hello to see how it works.
import discord
import asyncio
from discord.ext import commands
# you created 'client' and 'bot' and used them randomly. Create one and use it for everything:
client = commands.Bot(command_prefix="!") # you can change commands prefix here
#client.event
async def on_ready(): # this will run everytime bot is started
print('Logged as:', client.user)
print('ID:', client.user.id)
print('=' * 30)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'): # you can change what your bot should react to
await message.channel.send("Hello! (This is not a command. It will run everytime a user sends a message and it starts with `hello`).")
await client.process_commands(message)
#client.command()
async def example(ctx): # you can run this command by sending command name and prefix before it, (e.g. !example)
await ctx.send("Hey! This is an example command.")
client.run("YOUR TOKEN HERE")

Discord.py library sending message upon member update

this is how I've already tried getting the message channel that I would presume the discord server uses for this bot, from having used its other functionality:
#client.event
async def on_message(message):
global message_channel
message_channel = message.channel
I want to send a message saying goodbye to users when they go offline using this function
#client.event
async def on_member_update(before, after):
print(str(before.status), str(after.status))
if str(before.status) == "online" and str(after.status) == "offline":
print("someone went offline")
try: await message_channel.send(f'Goodbye, {after.user}')
except: print('failed to send goodbye message')
I'd appreciate either finding a way to make this work (since currently nothing at all prints from the on_member_update() function, or if I could get the channel that the last message was sent to from the bot (meaning this would only be in place once the bot is used at least once)
I think you should make a own channel for the goodbye messages or define a extra channel for it. This would look like this:
#client.event
async def on_message(message):
pass#your code here
#client.event
async def on_member_update(before, after):
print(str(before.status), str(after.status))
if str(before.status) == "online" and str(after.status) == "offline":
channel = cliet.get_channel(channelId)
print("someone went offline")
try:
await channel.send(f'Goodbye, {after.user}')
except:
print('failed to send goodbye message')
If you want to write the goodbye message in the channel the user last wrote in you can simply make a txt with the users and their last channels. You can also do this with json. If you do it in on_message you get the channel that was last typed in by anyone on the server OR in the dms of the bot. So if userXYZ wrote the BOT "Hello World" via DM and then another user userABC went offline the BOT will send userXYZ a Goodbye message via DM.

Discord.py: Why do the welcome and goodbye messages repeat?

Problem: I am trying to have it so that the bot sends a single message in general, but the messages continuously repeat, seemingly increasing each time this occurs. Also, if I switch the message to something else, the repeated parts are of the old message.
Code:
import discord
from discord.ext import commands
client=commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print('ok')
#client.event
async def on_member_join(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Hi {}".format(member))
#client.event
async def on_member_remove(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Bye")
client.run(token)
Since the code is under the function variable then you have to end each function.
It might be due to multiple instances of the application are running. Check your task manager and search for python process, End it if there are multiple and re-run the script.

Categories