HonusBot/inline.py

253 lines
7.0 KiB
Python
Raw Normal View History

2020-03-09 00:34:04 +01:00
# File: inline.py
# Description: Inline wrapper
2020-03-28 19:48:10 +01:00
# Author: Arves100
2020-05-05 12:02:41 +02:00
# Date: 25-12-2019 ~ 28-03-2020 . 29-04-2020
2019-12-28 21:57:04 +01:00
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
from telegram import InlineQueryResultArticle, InputTextMessageContent, Bot
import uuid
import requests
2020-03-12 00:29:20 +01:00
from telegram.utils.request import Request
2020-05-05 12:02:41 +02:00
import json
2019-12-28 21:57:04 +01:00
2020-05-05 12:02:41 +02:00
BOT_VERSION = "0.4"
2020-03-09 01:05:49 +01:00
class Command:
2019-12-28 21:57:04 +01:00
def __init__(self):
2020-03-09 01:05:49 +01:00
self.desc = ""
self.name = ""
self.headerField = ""
self.mode = ""
2019-12-28 21:57:04 +01:00
2020-03-09 02:13:48 +01:00
def __init__(self, name, desc, mode, hf):
self.desc = desc
self.name = name
self.headerField = hf
self.mode = mode
2020-03-09 01:05:49 +01:00
def setMode(self, mode):
self.mode = mode
def getMode(self):
return self.mode
def setDesc(self, desc):
self.desc = desc
def getDesc(self):
return self.desc
def getName(self):
return self.name
2019-12-28 21:57:04 +01:00
2020-03-09 01:05:49 +01:00
def setName(self, name):
self.name = name
2020-05-05 12:30:23 +02:00
2020-03-09 01:05:49 +01:00
def setHeaderField(self, param):
self.headerField = param
def getHeaderField(self):
return self.headerField
2020-03-09 01:18:21 +01:00
2020-05-05 12:02:41 +02:00
class JSONRequest(object):
2020-05-05 12:19:54 +02:00
def __init__(self, config, command, senderId, text):
2020-05-05 12:02:41 +02:00
self.botName = config.getApiId()
self.botPassword = config.getApiPassword()
self.command = command
self.replyToUserId = 0
self.senderUserId = senderId
self.chatId = 0
self.queryText = text
self.rawSingleArgument = False
class JSONResponse(object):
def __init__(self, auth, success, img, dsc):
self.auth = auth
self.success = success
self.imgUrl = img
self.htmlDesc = dsc
2020-05-05 17:21:36 +02:00
def isAuthorized(self):
2020-05-05 12:02:41 +02:00
return self.auth
2020-05-05 17:21:36 +02:00
def succeeded(self):
2020-05-05 12:02:41 +02:00
return self.success
2020-05-05 17:21:36 +02:00
def getHtmlDesc(self):
2020-05-05 12:02:41 +02:00
return self.htmlDesc
2020-05-05 17:21:36 +02:00
def getImageUrl(self):
2020-05-05 12:02:41 +02:00
return self.imgUrl
2020-03-09 01:18:21 +01:00
class Config:
def __init__(self):
self.apiUrl = ""
self.apiId = ""
self.apiPassword = ""
self.botToken = ""
def read(self, name):
import configparser
cfg = configparser.ConfigParser()
cfg.read(name)
self.apiUrl = cfg["Api"]["Url"]
self.apiId = cfg["Api"]["Id"]
self.apiPassword = cfg["Api"]["Password"]
self.botToken = cfg["Bot"]["Token"]
2020-03-11 02:39:26 +01:00
self.botConnectionPool = cfg["Bot"]["ConnectionPool"]
2020-05-05 12:02:41 +02:00
self.userAgent = cfg["Api"]["UserAgent"]
2020-03-09 01:18:21 +01:00
def getApiUrl(self):
return self.apiUrl
def getApiId(self):
return self.apiId
def getApiPassword(self):
return self.apiPassword
def getBotToken(self):
return self.botToken
2020-03-11 02:39:26 +01:00
def getBotConnectionPool(self):
return self.botConnectionPool
2020-05-05 12:02:41 +02:00
def getUserAgent(self):
return self.userAgent
2020-03-09 01:05:49 +01:00
2020-05-05 17:14:38 +02:00
def jsonasResponse(dct):
2020-05-06 19:39:38 +02:00
if not "imageUrl" in dct or not "htmlDescription" in dct:
2020-05-05 17:14:38 +02:00
raise Exception("Invalid JSON")
2020-05-06 19:39:38 +02:00
return JSONResponse(dct["authorized"], dct["success"], dct["imageUrl"], dct["htmlDescription"])
2020-05-05 17:14:38 +02:00
2020-03-09 01:05:49 +01:00
class InlineBot:
def __init__(self):
2019-12-28 21:57:04 +01:00
self.errorText = "Sowwy mawster, an ewror occuwed. ;;w;;"
2020-03-09 01:05:49 +01:00
self.commands = []
2020-03-09 01:18:21 +01:00
self.config = None
2020-03-09 01:05:49 +01:00
2020-03-09 01:40:39 +01:00
self.__loadConfig()
2020-03-09 01:05:49 +01:00
self.__makeCommands()
2019-12-28 21:57:04 +01:00
2020-03-09 01:18:21 +01:00
def __loadConfig(self):
self.config = Config()
self.config.read("config.ini")
2020-03-09 01:05:49 +01:00
def __makeCommands(self):
2020-05-05 18:07:20 +02:00
self.commands.append(Command("Pony", "yay, ponies!", "imageurl", "imageUrl"))
self.commands.append(Command("Clop", "NSFW ponies", "imageurl", "imageUrl"))
self.commands.append(Command("Furry", "Furries", "imageurl", "imageUrl"))
self.commands.append(Command("Loli", "Cute lolis", "imageurl", "imageUrl"))
self.commands.append(Command("Yiff", "Yiff", "imageurl", "imageUrl"))
self.commands.append(Command("Lewd", "Say hi to the police", "imageurl", "imageUrl"))
self.commands.append(Command("Rasoio", "Dai facciamogli lo scherzo del rasoio!1!!", "genericurl", "htmlDescription"))
2020-05-05 21:40:26 +02:00
self.cancerCommand = Command("Cancer", "Search cancer", "imageurl", "imageUrl")
2020-05-05 12:02:41 +02:00
2020-03-09 01:05:49 +01:00
def callRequest(self, command, senderid, text = ""):
if not command:
2020-05-05 12:34:22 +02:00
return None
2019-12-28 21:57:04 +01:00
2020-05-05 12:30:23 +02:00
r = requests.post(self.config.getApiUrl(), headers = { "Content-Type" : "application/json", "User-Agent" : self.config.getUserAgent() }, data = json.JSONEncoder().encode(JSONRequest(self.config, command.getName(), senderid, text).__dict__))
2020-05-05 12:02:41 +02:00
2020-05-05 12:34:22 +02:00
if not r:
2020-05-05 12:48:25 +02:00
self.logger.warning('Request api fail')
2020-05-05 12:34:22 +02:00
return None
2020-05-05 12:02:41 +02:00
if len(r.text) < 1:
2020-05-05 12:48:25 +02:00
self.logger.warning('Request text api fail')
2020-05-05 12:34:22 +02:00
return None
2019-12-28 21:57:04 +01:00
2020-05-05 12:02:41 +02:00
resp = None
2020-05-05 21:41:53 +02:00
try:
resp = json.loads(r.text, object_hook = jsonasResponse)
except:
self.logger.warning('JSON deserialization failed')
return None ## Invalid json
2020-05-05 12:02:41 +02:00
if not resp.isAuthorized() or not resp.succeeded():
2020-05-05 12:48:25 +02:00
self.logger.warning('Unathorized/Unsuccessfull')
2020-05-05 12:34:22 +02:00
return None
2019-12-28 21:57:04 +01:00
2020-05-05 21:40:26 +02:00
return resp
2019-12-28 21:57:04 +01:00
def start(self):
2020-03-11 02:39:26 +01:00
self.prequest = Request(con_pool_size=int(self.config.getBotConnectionPool()))
self.bot = Bot(token=self.config.getBotToken(), request=self.prequest)
2019-12-28 21:57:04 +01:00
self.updater = Updater(bot=self.bot,use_context=True)
2020-03-09 01:05:49 +01:00
print("Inline bot v. {}".format(BOT_VERSION))
2019-12-28 21:57:04 +01:00
self.dispatcher = self.updater.dispatcher
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
self.logger = logging.getLogger(__name__)
self.dispatcher.add_error_handler(self.errorHandler)
inline_caps_handler = InlineQueryHandler(self.inlineQuery)
self.dispatcher.add_handler(inline_caps_handler)
2020-03-09 01:05:49 +01:00
2019-12-28 21:57:04 +01:00
print("Started!")
2020-03-09 01:05:49 +01:00
2019-12-28 21:57:04 +01:00
self.updater.start_polling()
self.updater.idle()
def errorHandler(self, update, context):
"""Log Errors caused by Updates."""
2020-05-05 21:40:26 +02:00
self.logger.error('Update "%s" caused error "%s"', update, context.error)
2019-12-28 21:57:04 +01:00
def commandStart(self, update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Inline cancer, clop, furry spammer (h0nus)",parse_mode="HTML")
2020-03-09 01:05:49 +01:00
def makeResult(self, command, senderid, querySearch = ""):
2020-03-09 02:04:17 +01:00
if command == None:
2020-03-09 00:20:40 +01:00
return InlineQueryResultArticle(
id=uuid.uuid4().hex,
type="article",
2020-03-09 01:05:49 +01:00
title="Error",
input_message_content=InputTextMessageContent("Error", "HTML"),
description=self.errorText
2020-03-09 00:20:40 +01:00
)
2019-12-28 21:57:04 +01:00
2020-05-05 21:41:53 +02:00
resp = self.callRequest(command, senderid, querySearch)
2020-03-09 01:05:49 +01:00
contentText = ""
2020-05-05 12:34:22 +02:00
2020-05-05 21:41:53 +02:00
if resp == None:
2020-05-05 12:34:22 +02:00
return InlineQueryResultArticle(
id=uuid.uuid4().hex,
type="article",
title="Error",
input_message_content=InputTextMessageContent("Error", "HTML"),
description=self.errorText
)
2020-03-09 01:05:49 +01:00
if command.getMode() == "imageurl":
2020-05-05 21:40:26 +02:00
contentText = InputTextMessageContent("<a href=\"" + resp.getImageUrl() + "\">HonusBot</a>", "HTML")
2020-03-09 01:05:49 +01:00
elif command.getMode() == "genericurl":
2020-05-05 21:40:26 +02:00
contentText = InputTextMessageContent("<a href=\"" + resp.getHtmlDesc() + "\">link</a>", "HTML")
2020-03-09 01:05:49 +01:00
else:
contentText = InputTextMessageContent("Error", "HTML")
2019-12-28 21:57:04 +01:00
return InlineQueryResultArticle(
id=uuid.uuid4().hex,
type="article",
2020-03-09 01:05:49 +01:00
title=command.getName(),
2020-03-09 01:48:14 +01:00
input_message_content=contentText,
2020-03-09 01:05:49 +01:00
description=command.getDesc()
2019-12-28 21:57:04 +01:00
)
def inlineQuery(self, update, context):
senderid = str(update.inline_query.from_user.id)
query = update.inline_query.query
results = list()
if not query:
2020-03-09 01:05:49 +01:00
for command in self.commands:
2020-03-09 01:57:04 +01:00
results.append(self.makeResult(command, senderid))
2019-12-28 21:57:04 +01:00
else:
2020-03-11 02:01:37 +01:00
self.cancerCommand.setDesc("Search cancer about " + query)
2020-03-09 01:05:49 +01:00
results.append(self.makeResult(self.cancerCommand, senderid, query))
2019-12-28 21:57:04 +01:00
context.bot.answer_inline_query(update.inline_query.id, results, 1, False)
InlineBot().start()