How can I send a message without a command? - python

I want to send a message without command if a condition is true. I wrote this code but it doesn't send any message.
from discord import channel
from discord.ext import commands
from time import sleep
bot = commands.Bot(command_prefix='.')
token = '***'
condition = True
#bot.event
async def on_ready():
print('crypto-bot è pronto')
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content == '.ciao':
await message.channel.send('ciao')
async def my_background_task():
if condition == True:
channel = bot.get_channel(926067178539712512)
await channel.send('true')
bot.run(token)

async def my_background_task():
if condition == True:
channel = bot.get_channel(926067178539712512)
await channel.send('true')
await my_background_task()
I know for sure it wasnt working because you didnt trigger the function..but I dont know if this will work or not if this doesnt work trigger the function in the on_message function like this
async def on_message(message):
if message.author == bot.user:
return
if message.content == '.ciao':
await message.channel.send('ciao')
await my_background_task()

You can use tasks.loop for this. It will run every "x" seconds (in my example it's 5 seconds, but you can change it to minutes or hours).
from discord.ext import tasks # add this import
condition = True
#tasks.loop(seconds=5) # choose how often you want to run this function (e.g every 5 seconds)
async def my_background_task():
if condition == True:
channel = await bot.fetch_channel(926067178539712512)
await channel.send('true')
my_background_task.start() # put this before `bot.run(token)`
Like #l---Wernia---l noticed it will continue sending the message until the condition changes. If you want to send only one message then you have to change the condition to False.
#tasks.loop(seconds=5)
async def my_background_task():
global condition # if you want to change global variable inside the function you have to add this line
if condition == True:
channel = await bot.fetch_channel(926067178539712512)
await channel.send('true')
condition = False # changing condition at the end

Related

Discord.py: How can I make a toggleable system to turn on/off a message content detection?

I've been trying to work on a system where if you run the "AWM" command, the bot will check all further messages from anyone in a given server, if the message contains a key-phrase (in this case being 's') the bot will send "FlyingWiener go brrrrrrrrrrrrr" in the same channel as the message it found. But I don't know why my code isn't working, could I please have some help? Thanks!
def MessageContentDetection(): #on_message event definition where it detects "s" in a given message's content
#bot.event
def on_message(message):
if 's' in message.content:
await message.channel.send("FlyingWiener go brrrrrrrrrrrrr")
variables = {}
Messages = {}
#commands.command() #Activation Command
async def AWM(ctx):
User = ctx.author
Owner = ctx.guild.owner
if User == Owner:
var = variables.get(ctx.guild.id, 0)
if var == 0:
variables[ctx.guild.id] = 1
await ctx.send("WienerMode Now Active!")
Messages[ctx.guild.id] = 1
else:
await ctx.send("WienerMode is still active Sherlock")
else:
await ctx.send(f"Access Denied, No access granted to **{User}**")
#bot.event #Message Send Event
async def on_message(ctx):
MSG = Messages.get(ctx.guild.id, 0)
if MSG==1:
MessageContentDetection()
#commands.command() #Deactivation Command
async def DWM(ctx):
User = ctx.author
Owner = ctx.guild.owner
if User == Owner:
var = variables.get(ctx.guild.id, 0)
if var == 1:
variables[ctx.guild.id] = 0
await ctx.send("WienerMode Nolonger Active!")
Messages[ctx.guild.id] = 0
else:
await ctx.send("WienerMode is still off Idiot")
else:
await ctx.send(f"Access Denied, No access granted to **{User}**")```
You don't need the MessageContentDetection function, instead you should just check the condition inside the existing on_message event itself as the event is running either way. It can be done this way instead:
#bot.event
async def on_message(message):
if Messages.get(message.guid.id, 0) == 1:
if 's' in message.content:
await message.channel.send('FlyingWiener go brrrrrrrrrrrrr')
This way, if the condition isn't true, the on_message event will be passed and no code runs inside that.

Trying to randomize which function runs in discord.py But error occurs

import discord
from discord.ext import commands
import random
import time
client = commands.Bot(command_prefix = '')
x = 0
#client.event
async def on_message(self, message):
if message.author.id == client.user.id:
return
#client.event
async def on_ready():
print("bot is ready")
#client.command(aliases=['Signore'])
async def _summon(ctx):
await ctx.send('Ciao sono Signore Buffo')
#client.command(aliases=['Gib'])
async def common_phrases(ctx):
responses = [
'Si. Yes.',
'No. No.',
'Per favore. Please.',
'Grazie. Thank you.','Prego. Youre welcome.',
'Mi scusi. Excuse me.',
'Mi dispiace. I am sorry.',
'Buon giorno. Good morning.',
'Buona sera. Good evening.',
'Buona notte. Good night.'
]
await ctx.send(random.choice(responses))
#client.event
async def on_message(message):
if message.content == "please":
functions = [Hello(message), Test(message)]
await random.choice(functions)
#client.event
async def Hello(message):
if message.content == "quiz":
global x
x = 1
await message.channel.send('what is Hello in italian?')
time.sleep(2)
await message.channel.send('Would you like to know the answer? (y/n)')
if message.content == "y" and x == 1:
await message.channel.send('Ciao')
x = 0
#client.event
async def Test(message):
if message.content =="test":
global x
x = 2
await message.channel.send('This is a test')
time.sleep(2)
await message.channel.send('this is a test (2)')
if message.content == "bruh" and x == 2:
await message.channel.send('test complete')
x = 0
client.run('normally code here')
When I run the code and type "please" into discord it gives me the error:
RuntimeWarning: coroutine 'Hello' was never awaited
await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
I don't know how to fix this and I want to have a randomly chosen function run when I type "please". I tried to put the functions in a list and choose randomly between them. I think it's the on_message function which is giving me trouble. I am new to coding discord bots so this may be a really simple fix. Any help would be appreciated, thanks.
Look at this code:
#client.event
async def on_message(message):
if message.content == "please":
functions = [Hello(message), Test(message)]
await random.choice(functions)
That list doesn't store the address of the two functions, it actually CALLS both functions and stores their result. You want:
#client.event
async def on_message(message):
if message.content == "please":
functions = [Hello, Test]
await random.choice(functions)(message)
So, random.choice returns a function (we don't know which one), and we want to call that function and await the result.
That's a perfectly valid way to choose between several functions.

How to code yes/no function for discord bot

I wanted to code a function in which the bot sends the message 'happiness reloaded' when the user answers Y, or else it sends the message good night if the user answers N. I have tried to run this code, which replies to 'hi' but after that, when I type in Y or N, the bot cannot reply. My code example:
#client.event
async def on_message(message):
if message.author == client.user:
return
# if message.content.startswith('$inspire'):
# quote = get_quote()
# await message.channel.send(quote)
if message.content.startswith('hi'): # Delete this after testing
await message.channel.send('Congratulations! Your Disgotchi is hatched! (Play around? : Y/N)')
if message.content.includes('y', 'Y'):
await message.channel.send('Happiness reloaded! ( ^Θ^)❤️')
elif message.content.includes('n', 'N'):
await message.channel.send('I will go to bed, good night!')
should do what you want
all you have to do is store the ids outside the callback, expecting another message in same callback is useles as message newer changes
import discord
from discord.ext.commands import Bot
bot = Bot(command_prefix='$')
y_users = set() # set is best for this
#bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
#bot.event
async def on_message(message):
if message.content == 'hi':
await message.channel.send('Congratulations! Your Disgotchi is hatched! (Play around? : Y/N)')
y_users.add(message.author.id) # saving the id
# checking if id is in set which means user sent hello previously
elif (message.content.startswith('y', 'Y') and message.author.id in y_users):
await message.channel.send('Happiness reloaded! ( ^Θ^)❤️')
y_users.remove(message.author.id)
elif (message.content.startswith('n', 'N') and message.author.id in y_users):
await message.channel.send('I will go to bed, good night!')
y_users.remove(message.author.id)
bot.run("token")
please mark it as correct solution if it does what you want

Discord Bot in Python Reaction Response

I want that when someone reacts to one emoji the bot writes as a log on chat like this:
#Santa has press 4️⃣
I tried to make it but I'm stuck.
import discord
import time
import random
from discord.ext import commands
client = discord.Client()
bot = client.user
if message.content.startswith('ººrandgame'):
original = await message.channel.send('Discover the number I my mind...')
uno = await original.add_reaction('1️⃣')
dos = await original.add_reaction('2️⃣')
tres = await original.add_reaction('3️⃣')
cuatro = await original.add_reaction('4️⃣')
cinco = await original.add_reaction('5️⃣')
seis = await original.add_reaction('6️⃣')
siete = await original.add_reaction('7️⃣')
ocho = await original.add_reaction('8️⃣')
nueve = await original.add_reaction('9️⃣')
diez = await original.add_reaction('🔟')
numbers = ['1️⃣','2️⃣','3️⃣','4️⃣','5️⃣','6️⃣','7️⃣','8️⃣','9️⃣','🔟']
#this part fails::
if(reaction.emoji == "1️⃣"):
await message.channel.send(author + "has press 1️⃣")
#the same idea with the other numbers
time.sleep(15)
finalnum = random.choice(numbers)
await message.channel.send('My number is: ' + finalnum)
print(finalnum)
client.run('blabla')
You can use a reaction_wait_for, this will always wait for the author of the message input of the specified reaction.
Below I've made a simple user reaction command but I'll leave it up to you how you would further like to improve it.
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
In your code, I would also reccomend using asyncio.sleep(15) instead of time.sleep, as this causes the whole bot to stop, meaning no one can use it at all.
Make sure to import asyncio
You can also set it as a command, instead of using if message.content.startswith('ººrandgame'): , You can use
#client.command()
async def ººrandgame(ctx):
.... Rest of your code ...
Ibidem, I think that something is missing
import discord
import os
import random
import asyncio
from discord.ext import commands
client = discord.Client()
horaact = time.strftime('%H:%M:%S')
os.system('cls')
os.system('color 1f')
#client.event
async def on_ready():
print("Encendido")
print("logged in as {0.user}".format(client))
#client.command()
async def ººrandgame(ctx):
message = await ctx.send("React to a number")
one = '1️⃣'
two = '2️⃣'
await message.add_reaction(one)
await message.add_reaction(two)
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [one, two]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=600.0, check=check)
if str(reaction.emoji) == one:
await ctx.send("You choose 1")
if str(reaction.emoji) == two:
await ctx.send("You choose 2")
client.run('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
Remember, this is not the original code, it's just a test for trying your funtion

Unsure How to set a number to a variable python and how to make the bot notice every message

import random
import asyncio
import aiohttp
import json
from discord import Game
from discord.ext.commands import Bot
import discord
TOKEN = 'Token'
client = discord.Client()
botnum = 0
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('PeriBot'):
msg = "I'm Busy! D:<".format(message)
await client.send_message(message.channel, msg)
if discord.message and botnum == 20
msg = "You Clods are so loud!".format(message)
await client.send_message(message.channel, msg)
set botnum == 0
else:
botnum + 1
#client.event
async def on_ready():
print('Online and Ready to Play!')
print(client.user.name)
print(client.user.id)
await client.change_presence(game=discord.Game(name="With Emotions"))
print('------')
client.run("Token")
I want it to say a message every 20 messages but I am unsure how. I have somthing named botnum and it is == 0 and if there isn't 20 botnum's then it adds 1 to the botnum. If there is 20 it says a msg. I want it to add 1 to botnum every msg.
I'm noticing a lot of syntax errors in your code, I've updated it below with what it should look like, and noted the changes with ### at the end of the line where it was modified. As for "make them notice every message" I'll need some clarification and then update my answer if this doesn't suit your needs. I think the code I just provided should update the botnum with 1 every time a message is sent that isn't PeriBot which should solve your problem.
import random
import asyncio
import aiohttp
import discord
import json
from discord import Game
from discord.ext.commands import Bot
TOKEN = 'Token'
client = discord.Client()
#client.event
async def on_ready():
print('Online and Ready to Play!')
print(client.user.name)
print(client.user.id)
await client.change_presence(game=discord.Game(name="With Emotions"))
print('------')
botnum = 0
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
elif message.content.startswith('PeriBot'): ### Updated to elif which is more acceptable
msg = "I'm Busy! D:<".format(message)
await client.send_message(message.channel, msg)
elif discord.message and botnum == 20: ### forgot a ":" and Updated to elif which is more acceptable
msg = "You Clods are so loud!".format(message)
await client.send_message(message.channel, msg)
botnum = 0 ### you were comparing and not setting botnum to 0
else:
botnum += 1 ### This will add 1 to the preexisting number of botnum
client.run("Token")

Categories

Resources