I am creating a Telegram bot which would reply Hello in random languages. Is working fine but the problem is it replies even when I send something randomly with no meaning like sfdsfjls.
What should I do so that it replies only when I say Hi or Hello and reply something like I don't get it when I send something random.
I am using pytelegrambotapi.
My code:
import telebot
import random
bot_token =''
bot= telebot.TeleBot(token=bot_token)
lang1= ['Hola','Konnichiwa','Bonjour','Namaste']
# Handle normal messages
#bot.message_handler()
def send_welcome(message):
# Detect 'hi'
if message.text == 'hi' or 'hello':
bot.send_message(message.chat.id, (random.choice(lang1)))
You'll need
if message.text == 'hi' or message.text == 'hello':
Instead off
if message.text == 'hi' or 'hello':
Because the or 'hello' part will always result in TRUE as you can test here.
Another option, tho check if a string matches any other string could look something like this:
triggers = {'hi', 'hello'}
if message.text in triggers:
Applying those fixes, and adding a additional check based on the comment gives us the following code:
import telebot
import random
bot_token =''
bot= telebot.TeleBot(token=bot_token)
lang1= ['Hola','Konnichiwa','Bonjour','Namaste']
# Handle normal messages
#bot.message_handler()
def send_welcome(message):
# Detect Messages
if message.text == 'hi' or message.text == 'hello':
bot.send_message(message.chat.id, (random.choice(lang1)))
elif message.text == 'Test':
bot.send_message(message.chat.id, 'Test succeeded')
else:
bot.send_message(message.chat.id, 'Sorry I don\'t get it!')
Related
I'm trying to connect a wildlife camera to my SMTP server but it keeps dropping the connection after being asked for it's username. I've verified that this server works with other wildlife cameras and email clients but always seems to fail with this specific model of wildlife camera. I've tried with no authentication, basic authentication and TLS but none of them work (The camera works with gmail SMTP though).
This is the simple code I'm using.
It seems like I need to modify the challenge_auth method. My question is how do I do that, do I just add another method to the custom handler with handle_DATA in?
import email
from email.header import decode_header
from email import message_from_bytes
from email.policy import default
from aiosmtpd.controller import Controller
from aiosmtpd.smtp import LoginPassword, AuthResult
import os
import sys
import time
import signal
import logging
##setting timezone
os.environ['TZ'] = "Europe/London"
time.tzset()
def onExit( sig, func=None):
print("*************Stopping program*****************")
controller.stop()
exit()
signal.signal(signal.SIGTERM, onExit)
# removes the spaces and replaces with _ so they're valid folder names
def clean(text):
return "".join(c if c.isalnum() else "_" for c in text)
log = logging.getLogger('mail.log')
auth_db = {
b"TestCamera1#gmail.com": b"password1",
b"user2": b"password2",
b"TestCamera1": b"password1",
}
def authenticator_func(server, session, envelope, mechanism, auth_data):
#this deliberately lets everything through
assert isinstance(auth_data, LoginPassword)
username = auth_data.login
password = auth_data.password
return AuthResult(success=True)
def configure_logging():
file_handler = logging.FileHandler("aiosmtpd.log", "a")
stderr_handler = logging.StreamHandler(sys.stderr)
logger = logging.getLogger("mail.log")
fmt = "[%(asctime)s %(levelname)s] %(message)s"
datefmt = None
formatter = logging.Formatter(fmt, datefmt, "%")
stderr_handler.setFormatter(formatter)
logger.addHandler(stderr_handler)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG)
class CustomHandler:
def handle_exception(self, error):
print("exception occured")
print(error)
return '542 Internal Server Error'
async def handle_DATA(self, server, session, envelope):
peer = session.peer
data = envelope.content # type: bytes
msg = message_from_bytes(envelope.content, policy=default)
# decode the email subject
print("Msg:{}".format(msg))
print("Data:{}".format(data))
print("All of the relevant data has been extracted from the email")
return '250 OK'
if __name__ == '__main__':
configure_logging()
handler = CustomHandler()
#update hostname to your IP
controller = Controller(handler, hostname='0.0.0.0', port=587, authenticator=authenticator_func, auth_required=True,auth_require_tls=False)
# Run the event loop in a separate thread.
controller.start()
while True:
time.sleep(10)
Here's the logs from a reolink go camera that can connect successfully. (I've updated the format 'Username' is being send .e.g from 'User Name:' to 'Username' by editing the library but that hasn't seemed to help with the suntek camera. I thought it might be more pick with the format due to cheaper, less robust firmware.
I am creating a Telegram bot using pytelegrambotapi. But when I test the code, my Telegram Bot always replies with quoting my input like this, I don't want it to quote my input message but send the message directly.
Also how can I get replies by just using simple Hi or Hello not /hi or /hello.
My Code:
import telebot
import time
bot_token = ''
bot= telebot.TeleBot(token=bot_token)
#bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, 'Hi')
#bot.message_handler(commands=['help'])
def send_welcome(message):
bot.reply_to(message, 'Read my description')
while True:
try:
bot.polling()
except Exception:
time.sleep(10)
I don't want it to quote my input message but send the message directly.
bot.reply_to replies to the message itself. If you wish to send a separate message, use bot.send_message. You'll need to pass the ID of the user you're wishing to send a message to. You can find this id on message.chat.id so you're sending the message to the same chat.
#bot.message_handler(commands=['help'])
def send_welcome(message):
# Reply to message
bot.reply_to(message, 'This is a reply')
# Send message to person
bot.send_message(message.chat.id, 'This is a seperate message')
Also how can I get replies by just using simple Hi or Hello not /hi or /hello.
Instead off using a message_handler with a commands=['help'] you can remove the parameter to catch each message not catched by any command message handler.
Example with above implemented:
import telebot
bot_token = '12345'
bot = telebot.TeleBot(token=bot_token)
# Handle /help
#bot.message_handler(commands=['help'])
def send_welcome(message):
# Reply to message
bot.reply_to(message, 'This is a reply')
# Send message to person
bot.send_message(message.chat.id, 'This is a seperate message')
# Handle normal messages
#bot.message_handler()
def send_normal(message):
# Detect 'hi'
if message.text == 'hi':
bot.send_message(message.chat.id, 'Reply on hi')
# Detect 'help'
if message.text == 'help':
bot.send_message(message.chat.id, 'Reply on help')
bot.polling()
Visual result:
If i understood corectly:
cid = message.chat.id
bot.send_message(cid, "Hello")
I'm making a discord bot that worked fine but I wanted to start using cogs because I thought it was a nicer way to write my code but now my on_message doesn't work any more and it doesn't show any error messages I searched how to fix it in the whole internet and all explanations didn't work for me so I decided to ask here. So here is my code:
from discord.ext import commands
TOKEN = 'my token'
bot = commands.Bot(command_prefix="$")
class Interactions(commands.Cog):
#commands.Cog.listener()
async def on_message(self, message):
msg = message.content
hi = ["hi", "hello", "hi!", "hello!"]
bye = ["bye", "good bye", "bye!", "good bye!"]
# Messages in english
if str(msg).lower() in hi:
await message.channel.send('Hello!')
if str(msg).lower == 'how are you?':
await message.channel.send("I'm fine")
if str(msg).lower == "what's your favorite food?":
await message.channel.send("Sushi with sweet potato!")
if str(msg).lower == "what do you eat?":
await message.channel.send(
"I don't eat, I'm just a simple bot :pensive:")
if str(msg).lower == "are you fine?":
await message.channel.send("Yes, I am")
if str(msg).lower in bye:
await message.channel.send("Good bye!")
def run():
bot.add_cog(Interactions(bot)
bot.run(TOKEN)
if __name__ == "__main__":
run()
Import:
from discord.ext.commands import command, Cog
Rest of the code:
TOKEN = 'my token'
bot = commands.Bot(command_prefix="$")
class Interactions(commands.Cog):
#commands.Cog.listener()
async def on_message(self, message):
pass
This should work, if not just ping me ;)
I made a discord selfbot that should detect every sent message and respond randomly to it. However, when I put it in a server with 450k people it only can detect those messages if they mention the account. This is the code
import os
import discord
import time
import random
import string
from discord.utils import get
from discord.ext import commands
TOKEN = "suwhgiowejvoifghoirwfofrgowegvofdgrovugdgovjfeogjrwo"
client=commands.Bot(command_prefix='', self_bot=True, fetch_offline_members=False)
#client.event
async def on_ready():
print('connected to Discord!')
#client.event
async def on_message(message):
print('message received')
time.sleep(60)
response=[
'hi',
'hello',
'interesting',
'no',
'bruh',
'.',
'oof',
'lol',
'lmao',
'yeah'
]
try:
await message.channel.send(random.choice(response))
print('message sent')
except:
print("message error")
pass
client.run(TOKEN, bot=False)
The issue is probably just that there are way too many people and it won't work. However, if you think that it may be something else please let me know.
(I know selfbots are against the ToS and that my account could get banned please don't get pissed at me)
It could be with the fetch_offline_members=False or the time.sleep(60), I can't think of sth else
Currently I'm writing my first Telegram bot.
It should send a message to new users.
Other users should not get spammed by these messages and therefore I want to send it only to the new user.
I already have:
def switch(update, context):
try:
for new_member in update.message.new_chat_members:
callback_id = str(new_member.id)
# This is where I'm stuck
except AttributeError:
pass
def main():
updater = Updater(str(TOKEN), use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.chat(int(CHAT_ID)), switch))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
It runs until the commented line when a new user enters the chat.
Now I'm searching for the method to send a message to the new user only.