Skip to content

Instantly share code, notes, and snippets.

@Apoorve73
Last active January 2, 2021 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Apoorve73/f3c0e24020cb0f20010326093a1ce578 to your computer and use it in GitHub Desktop.
Save Apoorve73/f3c0e24020cb0f20010326093a1ce578 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
import requests
import re
import random
import converse
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
GENDER, PHOTO, LOCATION, BIO = range(4)
BREAKINGNEWS = range(1)
# LYRICS = range(1)
#
# def get(update, context):
# user = update.message.from_user
# chat_id = update.message.chat_id
# update.message.reply_text("Send me the song name for lyrics!")
#
# return LYRICS
#
# def lyrics(update,context):
# user = update.message.from_user
# name = update.message.text
# import requests
# data = {
# 'q': name,
# 'api_token': ''
# }
# result = requests.post('https://api.audd.io/findLyrics/', data=data)
# res_txt = result.json()
# logger.info("qyery of %s: %s", user.first_name, name)
# update.message.reply_text(res_txt["result"][0]["lyrics"])
def breaking_news(update,context):
user = update.message.from_user.first_name
category_sel = update.message.text
logger.info("News query of %s: %s", user, category_sel)
target = category_sel.lower()
url = 'http://newsapi.org/v2/top-headlines?country=in&category=' + target + '&apiKey=ef4ad46913774ede88fca1adf753a71b'
response = requests.get(url).json()
resp = response['articles']
for i in range(3):
update.message.reply_text('Headline : ' + resp[i]['title'] + '\n\nLink to full report: ' + resp[i]['url']
, reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def category(update, context):
reply_keyboard = [['Technology', 'Sports', 'Business', 'Entertainment', 'Science', 'Health']]
update.message.reply_text(
'Nice to meet you newsophile!\n\n'
'Choose between the categories below to get the Top 3 BREAKING NEWS headlines in India.',
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
return BREAKINGNEWS
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_image_url():
allowed_extension = ['jpg','jpeg','png']
file_extension = ''
while file_extension not in allowed_extension:
url = get_url()
file_extension = re.search("([^.]*)$",url).group(1).lower()
return url
def dogu(update, context):
url = get_url()
chat_id = update.message.chat_id
user = update.message.from_user
print("dog query by : " + user.first_name)
context.bot.sendPhoto(chat_id=chat_id, photo=url)
# For bad memes api
def meme(update,context):
url = "https://api.imgflip.com/get_memes"
contents = requests.get(url).json()
target = contents['data']['memes'][random.randint(0, 99)]['url']
target_name = contents['data']['memes'][random.randint(0, 99)]['name']
name = update.message.from_user.first_name
chat_id = update.message.chat_id
print("meme query by {}".format(name))
context.bot.sendPhoto(chat_id=chat_id, photo=target)
update.message.reply_text(target_name)
#quotes api
def quotes(update,context):
url = "https://opinionated-quotes-api.gigalixirapp.com/v1/quotes?rand=t&n=295"
contents = requests.get(url).json()
quote = contents['quotes'][random.randint(0, 294)]['quote']
author = contents['quotes'][random.randint(0, 294)]['author']
name = update.message.from_user.first_name
chat_id = update.message.chat_id
print("quote query by {}".format(name))
update.message.reply_text('Quote : ' + quote)
update.message.reply_text('Author : ' + author)
def start(update, context):
"""Send a message when the command /start is issued."""
user = update.message.from_user
update.message.reply_text('Hi! ' + user.first_name)
def bye(update, context):
user = update.message.from_user
update.message.reply_text('Bye! ' + user.first_name + ".Will wait for you, probably with a better version of mine :)")
def help_command(update, context):
"""Send a message when the command /help is issued."""
user = update.message.from_user
update.message.reply_text('Its my pleasure '+ user.first_name + ".I can help you with other commands! Try them :)")
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', converse.start)],
states={
GENDER: [MessageHandler(Filters.regex('^(Boy|Girl|Other)$'), converse.gender)],
PHOTO: [MessageHandler(Filters.photo, converse.photo),
CommandHandler('skip', converse.skip_photo)],
LOCATION: [MessageHandler(Filters.location, converse.location),
CommandHandler('skip', converse.skip_location)],
BIO: [MessageHandler(Filters.text, converse.bio)]
},
fallbacks=[CommandHandler('cancel', converse.cancel)]
)
dp.add_handler(conv_handler)
'''
This is the code for news api below
'''
news_handler = ConversationHandler(
entry_points=[CommandHandler('news', category)],
states={
# ^ asserts start of the line while $ assert the end of line
BREAKINGNEWS: [MessageHandler(Filters.regex('^(Technology|Sports|Business|Science|Entertainment|Health)$'),
breaking_news)],
},
fallbacks=[CommandHandler('cancel', converse.cancel)]
)
dp.add_handler(news_handler)
# lyr_handler = ConversationHandler(
# entry_points=[CommandHandler('lyrics', get)],
# states={
# LYRICS: [MessageHandler(Filters.text, lyrics)]
# },
# fallbacks=[CommandHandler('cancel', converse.cancel)]
# )
#
# dp.add_handler(lyr_handler)
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("greet", start))
dp.add_handler(CommandHandler("bye", bye))
dp.add_handler(CommandHandler("help", help_command))
dp.add_handler(CommandHandler('dogu', dogu))
dp.add_handler(CommandHandler("badmeme", meme))
dp.add_handler(CommandHandler("quote", quotes))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.chat(938773361), echo))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment