Example #1
0
import re
import random
import ast

from aiotg import Bot, chat
from database import db, text_search, text_delete

if os.environ.get('LANG') == 'zh-TW':
    from zh_TW import greeting, help, not_found, texts
elif os.environ.get('LANG') == 'en-US':
    from en_US import greeting, help, not_found, texts
else:
    from zh_TW import greeting, help, not_found, texts

bot = Bot(api_token=os.environ.get('API_TOKEN'),
          name=os.environ.get('BOT_NAME'),
          botan_token=os.environ.get("BOTAN_TOKEN"))
logger = logging.getLogger("musicbot")
channel = bot.channel(os.environ.get('CHANNEL'))
logChannelID = os.environ.get("LOGCHN_ID")


async def getAdmin(ID=logChannelID):
    raw = ast.literal_eval(
        str(await bot.api_call("getChatAdministrators", chat_id=ID)))
    i = 0
    adminDict = []
    while i < len(raw['result']):
        if 'last_name' in raw['result'][i]['user']:
            adminDict.append({
                'id':
Example #2
0
import os

import imageio
from aiotg import Bot, Chat

from services import ClassifyModel, get_square

model = ClassifyModel()

bot = Bot(api_token=os.getenv('TG_TOKEN'))


@bot.command('/start')
async def start(chat: Chat, match):
    return chat.reply('Send me photo of ant or bee.')


@bot.handle('photo')
async def handle_photo(chat: Chat, photos):
    # Get image binary data
    meta = await bot.get_file(photos[-1]['file_id'])
    resp = await bot.download_file(meta['file_path'])
    data = await resp.read()

    # Convert binary data to numpy.ndarray image
    image = imageio.imread(data)

    # Do the magic
    tag = await model.predict.call(image)

    # Simple text response
Example #3
0
import os
from aiotg import Bot

bot = Bot(api_token="API_TOKEN")


@bot.command("whoami")
def whoami(chat, match):
    return chat.reply(chat.sender["id"])


if __name__ == "__main__":
    bot.run(debug=True)
Example #4
0
from aiotg import Bot, Chat

from mailtrackingbot.config import config

bot = Bot(api_token=config.get('telegram', 'api_token'))


@bot.command(r"/echo (.+)")
def echo(chat: Chat, match):
    return chat.reply(match.group(1))


if __name__ == '__main__':
    bot.run()
Example #5
0
if len(sys.argv) < 2:
    print('usage: python simple.py simple.conf')
    sys.exit(1)
conf = sys.argv[1]
config = configparser.ConfigParser()
config.read(conf)
BOT_TOKEN = config.get('telegram', 'bot_token', fallback='')
ADMIN_ID = int(config.get('telegram', 'admin_id', fallback=0))
PROXY = config.get('telegram', 'proxy', fallback=None)
ADDRESS = config.get('ipc', 'address', fallback='http://127.0.0.1:1242/')
PASSWORD = config.get('ipc', 'password', fallback='')

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger('simple_asf_bot')

bot = Bot(api_token=BOT_TOKEN, proxy=PROXY)


async def command(asf, cmd):
    return await asf.Api.Command.post(body={
        'Command': cmd
    })


async def main():
    async with IPC(ipc=ADDRESS, password=PASSWORD) as asf:
        @bot.command(r'^([^/].*)$')
        async def message(chat: Chat, match):
            sender = chat.sender['id']
            logger.info(f'Get {match.group(1)}')
            if sender == ADMIN_ID:
Example #6
0
        MATRIX_PREFIX = MATRIX_HOST + '_matrix/client/r0/'
        MATRIX_MEDIA_PREFIX = MATRIX_HOST + '_matrix/media/r0/'

        USER_ID_FORMAT = CONFIG['user_id_format']

        TELEGRAM_CHATS = CONFIG['chats']
        MATRIX_ROOMS = {v: k for k, v in TELEGRAM_CHATS.items()}
except (OSError, IOError) as exception:
    print('Error opening config file:')
    print(exception)
    exit(1)

GOO_GL_URL = 'https://www.googleapis.com/urlshortener/v1/url'

TG_BOT = Bot(api_token=TG_TOKEN)
MATRIX_SESS = ClientSession()
SHORTEN_SESS = ClientSession()


def create_response(code, obj):
    """
    Create an HTTP response with a JSON body.
    :param code: The status code of the response.
    :param obj: The object to serialize and include in the response.
    :return: A web.Response.
    """
    return web.Response(text=json.dumps(obj),
                        status=code,
                        content_type='application/json',
                        charset='utf-8')
Example #7
0
    "desc": ["搞笑动态图片", "尴尬囧图", "美女福利图", "开开心心 轻松一刻", "爆笑冷知识", "日式冷吐槽"],
    "dynamic":
    "http://www.gamersky.com/ent/111/",
    "oops":
    "http://www.gamersky.com/ent/147/",
    "beauty":
    "http://tag.gamersky.com/news/1626.html",
    "easy_moment":
    "http://www.gamersky.com/ent/20503/",
    "cold_tucao":
    "http://www.gamersky.com/ent/20108/",
    "trivia":
    "http://www.gamersky.com/ent/198/"
}

bot = Bot(api_token=token)
root_url = "http://www.gamersky.com/ent/"
help_tetx = "点击按钮查看下一页, 或者点击原网址查看详细内容"


@bot.command(r"/start")
async def list_category(chat: Chat, match):
    kb, row = [], -1
    for idx, item in enumerate(category["name"]):
        if idx % 2 == 0:
            kb.append([])
            row += 1
        kb[row].append(item)
    keyboard = {"keyboard": kb, "resize_keyboard": True}
    text = "请选择你喜欢的图片类型,动态图和冷知识还有bug,其他类型都能正常查看"
    message = await chat.send_text(text=text,
Example #8
0
TOKEN = os.environ["PP_BOT_TOKEN"]
DB_PATH = os.environ.get("PP_BOT_DB_PATH",
                         os.path.expanduser("~/.tg_pp_bot.db"))
GREETING = """
Use 
/poker task url or description 
to start game.

Multiline is also supported
/poker line1
line2
Currently there is only one scale: 1, 2, 3, 5, 8, 13, 20, 40, ❔, ☕
"""

bot = Bot(TOKEN)
storage = GameRegistry()
init_logging()
REVEAL_RESTART_COMMANDS = [
    Game.OP_REVEAL, Game.OP_RESTART, Game.OP_RESTART_NEW, Game.OP_REVEAL_NEW
]


@bot.command("/start")
@bot.command("/?help")
async def start_poker(chat: Chat, match):
    await chat.send_text(GREETING)


@bot.command("(?s)/poker\s+(.+)$")
@bot.command("/(poker)$")
Example #9
0
 def __init__(self):
     self._bot = Bot(conf.bot_token, proxy=conf.tele_proxy)
     self.session = self._bot.session
     self.loop = self._bot.loop
     self.init_handlers()
Example #10
0
not_found = """
找不到資料 :/
"""
bye = """
掰掰! 😢
"""

global host
global api
host = os.environ.get('HOST')
api = os.environ.get('API')
logger = logging.getLogger(os.environ.get('BOT_NAME_EN'))
logChannelID = os.environ.get('LOGCHANNELID')
bot = Bot(
    api_token=os.environ.get('TOKEN'),
    name=os.environ.get('BOT_NAME_TW'),
)

async def getAdmin(ID=logChannelID):
    raw = ast.literal_eval(str(await bot.api_call("getChatAdministrators",chat_id=ID)))
    adminDict = [{
        'id':i['user']['id'],
        'username':i['user']['username'],
        'first_name':i['user']['first_name'],
        'last_name':i['user']['last_name'] if 'last_name' in i['user'] else ''
    } for i in raw['result']]
    return adminDict

async def isAdmin(ID):
    adminList = await getAdmin()
    ]

    return chat.reply('\n'.join([
        "Hello! This bot lets you subscribe to various feeds.",
        "Here's the commands:", *command_docstrings,
        "This bot is being worked on, so it may break sometimes. "
        "Contact @franciscod if you want to chat about it!"
    ]))


def base_bootup(bot):
    bot.default(default)
    bot.command("/listsubs")(listsubs)
    bot.command("/export")(export)
    bot.command("/unsub$")(unsub)
    bot.command("/unsub_(.*)")(unsub_do)
    bot.command("/wipe")(wipe)
    bot.command("/source")(source)
    bot.command('/help')(help)
    bot.command('/start')(help)
    pass


if __name__ == '__main__':
    models.create_tables()
    bot = Bot(os.environ["TG_BOT_TOKEN"])
    resources.Clock.bootup(bot)

    base_bootup(bot)
    bot.run()
Example #12
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import asyncio
import signal
from time import time

import aioredis
import ujson as json
import uvloop
from aiotg import Bot, Chat
from bismillahbot import Quran, make_index

from secret import token


bot = Bot(api_token=832354568:AAF-0KaBTXkrQF7eY18Bk5_jOTxK8usfpDk, json_serialize=json.dumps, json_deserialize=json.loads)
quran_index = make_index()
redis = None
redis_namespace = "aqb:"


def get_file(filename: str):
    return redis.get(redis_namespace + filename)


def save_file(filename: str, file_id: str):
    return redis.set(redis_namespace + filename, file_id, expire=60*60*24*30)


@bot.command(r"/(?:start|help)")
def usage(chat: Chat, match):
Example #13
0
from aiotg import Bot
from bs4 import BeautifulSoup
import re
import requests
import random

bot = Bot(api_token="198167022:AAGAsVWecf6y_Ul3e9BdleEirSxbH6HI1xs")

hello_message = '<b>Добро пожаловать!</b>\n ' \
                'Я - бот для поиска очень вкусных рецептов самых разнообразных блюд. \n ' \
                '/help - если хотите узнать команды, которыми я владею'


help_message = '/recipe название_блюда  -  <b>поиск любого блюда</b> \n' \
               '/details название_блюда желаемые_ингредиенты исключаемые_ингредиенты сложность - <b>подробное описание нужного блюда</b> \n' \
               'Если вы не хотите задавать какой-то параметр, напишите на его месте <b> - </b>\n' \
               'Если рецепт вам не понравился, повторите команду и вам будет предложен другой вариант\n' \
               '/dayrecipe - Рецепт дня\n' \
               '/start - стартовая страница и информация о боте'


def get_page(food, iningr, exingr, diff):
    url = 'http://www.gastronom.ru/search/type/recipe/?t=&title={food}&iningr={iningr}&exingr={exingr}&diff={diff}'.\
        format(food=food, iningr=iningr, exingr=exingr, diff=diff)
    response = requests.get(url)
    web_page = response.text
    soup = BeautifulSoup(web_page, 'html5lib')
    tags = soup.find("div", class_="tags")
    tags = tags.find("span",
                     class_="big-tag big-tag__muted myFixTag").text.split(": ")
    if int(tags[1]) != 0:
Example #14
0
import logging

from aioredis import create_redis_pool, Redis
from aiotg import Chat, Bot

from trading_bot.manager import Manager, State
from trading_bot.settings import dev_hooks_token, chatbase_token, proxy_string
from trading_bot.sources.sources import SmartLab
from trading_bot.telegram_helper import keyboard_markup, build_menu

log = logging.getLogger(__name__)

bot = Bot(
    api_token=dev_hooks_token,
    chatbase_token=chatbase_token,
    name="TradingNewsBot",
    proxy=proxy_string,
)

manager = None


async def init(host):
    global manager

    redis: Redis = await create_redis_pool(host, minsize=5, maxsize=10)
    manager = Manager(redis=redis)

    async for chat_id, data in manager.check_new_all(save=False):
        pass
Example #15
0
import pytest
import random

from aiotg import Bot, Chat, InlineQuery
from aiotg import MESSAGE_TYPES, MESSAGE_UPDATES
from aiotg.mock import MockBot
from testfixtures import LogCapture

API_TOKEN = "test_token"
bot = Bot(API_TOKEN)


def custom_msg(msg):
    template = {
        "message_id": 0,
        "from": {
            "first_name": "John"
        },
        "chat": {
            "id": 0,
            "type": "private"
        }
    }
    template.update(msg)
    return template


def text_msg(text):
    return custom_msg({"text": text})

Example #16
0
By default, the search is fuzzy but you can use double quotes to filter results:
"summer of haze"
"sad family"

To make an even stricter search, just quote both terms:
"aes dana" "haze"
"""

not_found = """
We don't have anything matching your search yet :/
But you can fix it by sending us the tracks you love as audio files!
"""


bot = Bot(
    api_token=os.environ.get("API_TOKEN"),
    name=os.environ.get("BOT_NAME"),
    )
logger = logging.getLogger("musicbot")


@bot.handle("audio")
async def add_track(chat, audio):
    if (await db.tracks.find_one({ "file_id": audio["file_id"] })):
        return

    if "title" not in audio:
        await chat.send_text("Sorry, but your track is missing title")
        return

    doc = audio.copy()
    doc["sender"] = chat.sender["id"]
Example #17
0
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-

from aiotg import Bot, Chat

from models import HistoryLogger

import constants as c
import logging

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)

bot = Bot(api_token=c.TOKEN)


@bot.command("start")
def start(chat: Chat, match):
    """
    Hello, it's me!
    """
    if c.START_MSG:
        return chat.reply(c.START_MSG)


@bot.command("whoami")
def whoami(chat: Chat, match):
    """
    [For debug purposes only] Get telegram user id
Example #18
0
import textwrap
import random

# Bot
from aiotg import Bot

# Queries
from database.queries import user_exists, insert_user, deactivate_user
from database.queries import insert_text

# Variables
api_token = os.environ.get("API_TOKEN")
bot_name = os.environ.get("BOT_NAME")

# Bot
bot = Bot(api_token=api_token, name=bot_name)

# Logging
logger = logging.getLogger("bot")
logging.basicConfig(level=logging.DEBUG)


def format_text(text):
    return textwrap.dedent(text)


@bot.handle("new_chat_member")
async def new_chat_member_event(chat, member):
    logger.info("New chat member %s joined group", member["first_name"])
    text = format_text("""
    {greet}, {name}!
Example #19
0
def main():
    """Main app"""
    logger = init_logger()

    # Loading settings
    try:
        setting = {
            "token": os.environ["FWD_TOKEN"],
            "keys_path": os.environ["FWD_KEYS_PATH"],
            "salt": int(os.environ["FWD_SALT"]),
            "webhook_url": os.environ["FWD_WEBHOOK_URL"],
            "listen_addr": os.environ.get("FWD_LISTEN_ADDR", "127.0.0.1"),
            "listen_port": int(os.environ.get("FWD_LISTEN_PORT", 8080)),
        }
    except KeyError as err:
        logger.critical("Setting %s not found. Exit!", err)
        sys.exit(1)
    except ValueError:
        logger.critical(
            "Invalid setting value. Check `FWD_SALT` or `FWD_LISTEN_PORT`. Exit!"
        )
        sys.exit(1)

    # Init token module
    base_dir = os.path.realpath(setting["keys_path"])
    if not os.path.isdir(base_dir):
        logger.critical("Invalid directory in `FWD_KEYS_PATH`: %s", base_dir)
        sys.exit(1)

    token = Token(pub_key_path=os.path.join(base_dir, "fwd_pub.pem"),
                  priv_key_path=os.path.join(base_dir, "fwd_priv.pem"),
                  salt=setting["salt"])

    # Init bot module
    parsed_url = urlparse(setting["webhook_url"])
    bot = Bot(api_token=setting["token"])
    bot_handlers = BotHandlers(
        token=token,
        base_api_url="{p.scheme}://{p.netloc}".format(p=parsed_url))

    bot.add_command("token", bot_handlers.token_handler)
    bot.add_command("ping", bot_handlers.ping_handler)
    bot.add_command("help", bot_handlers.help_handler)

    try:
        logger.info("Register webhook...")
        bot.set_webhook(setting["webhook_url"])
        logger.info("Register webhook... OK!")
    except BotApiError as err:
        logger.error("Register webhook... ERROR!")
        logger.critical("Unable to register webhook: %s", err)
        sys.exit(2)

    # Init web app
    app = web.Application()
    app["bot"] = bot
    app.on_cleanup.append(bot_shutdown)

    web_handlers = RestHandlers(token=token, bot=bot)
    app.add_routes([
        web.post("/in", web_handlers.incomming_message),
        web.get("/v1/message", web_handlers.send_message),
        web.post("/v1/message", web_handlers.send_message),
        web.put("/v1/message", web_handlers.update_message),
        web.delete("/v1/message", web_handlers.delete_message),
    ])

    web.run_app(app,
                host=setting["listen_addr"],
                port=setting["listen_port"],
                access_log=logger)

    logger.info("Web application closed. Exit!")
Example #20
0
import json
import os
from aiotg import Bot

bot = Bot(api_token=os.environ["API_TOKEN"])


@bot.command(r'/start')
def start(chat, match):

    markup = {
        'type':
        'InlineKeyboardMarkup',
        'inline_keyboard': [
            [{
                'type': 'InlineKeyboardButton',
                'text': 'Button A',
                'callback_data': 'buttonclick-A'
            }, {
                'type': 'InlineKeyboardButton',
                'text': 'Button B',
                'callback_data': 'buttonclick-B'
            }],
            [{
                'type': 'InlineKeyboardButton',
                'text': 'Nohandle Button',
                'callback_data': 'no_callback_data'
            }],
        ]
    }
Example #21
0
"summer of haze"
"sad family"

To make an even stricter search, just quote both terms:
"aes dana" "haze"
"""

not_found = """
We don't have anything matching your search yet :/
But you can fix it by sending us the tracks you love as audio files!
"""


bot = Bot(
    api_token=os.environ.get("1691371768:AAE1T-ieS89l1JKAi6dNOutknH_It7aMDWc"),
    name=os.environ.get("SuabruMBot"),
    botan_token=os.environ.get("BOTAN_TOKEN")
)
logger = logging.getLogger("musicbot")


@bot.handle("audio")
async def add_track(chat, audio):
    if (await db.tracks.find_one({ "file_id": audio["file_id"] })):
        return

    if "title" not in audio:
        await chat.send_text("Sorry, but your track is missing title")
        return

    doc = audio.copy()
Example #22
0
from aiotg import Bot, Chat
import asyncio
import os
import regex as re
from collections import defaultdict, deque
from pprint import pprint

bot = Bot(api_token=os.environ['API_KEY'])

last_msgs = defaultdict(lambda: deque(maxlen=10))


def find_original(message):
    if 'text' in message:
        return message['text']
    elif 'caption' in message:
        return message['caption']

    return None


async def doit(chat, match):
    fr = match.group(1)
    to = match.group(2)
    to = to.replace('\\/', '/')
    try:
        fl = match.group(3)
        if fl == None:
            fl = ''
        fl = fl[1:]
    except IndexError:
Example #23
0
import os
import asyncio
from aiohttp import web
from aiotg import Bot, Chat, InlineQuery, CallbackQuery
from klocmod import LocalizationsContainer

import msgdb
import strconv
from txtproc import TextProcessorsLoader, TextProcessor
from txtprocutil import resolve_text_processor_name
from data.config import *
from queryutil import *

DECRYPT_BUTTON_CACHE_TIME = 3600  # in seconds

bot = Bot(api_token=TOKEN, default_in_groups=True)
localizations = LocalizationsContainer.from_file("app/localizations.ini")
text_processors = TextProcessorsLoader(strconv)


@bot.command("/start")
@bot.command("/help")
@bot.default
async def start(chat: Chat, _) -> None:
    lang = localizations.get_lang(chat.message['from']['language_code'])
    await chat.send_text(lang['help_message'])
    await chat.send_text(lang['help_message_transformers_list'])
    for processor in text_processors.all_processors:
        help_message_key = 'help_' + processor.snake_case_name
        localized_help_message = lang[help_message_key]
        # skip empty and undefined help messages
Example #24
0
import os
from aiotg import Bot

bot = Bot(os.environ["API_TOKEN"])


@bot.command(r"bitcoin")
async def bitcoin(chat, match):
    url = "https://api.bitcoinaverage.com/ticker/global/USD/"
    async with bot.session.get(url) as s:
        info = await s.json()
        await chat.send_text(info["24h_avg"])


if __name__ == '__main__':
    bot.run(debug=True)
Example #25
0
import asyncio
import logging

from aiotg import Bot, Chat

import db
import settings
from exchanges import get_api_by_name, get_supported_info
from order_checker import OrderChecker

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(settings.BOT_NAME)

bot = Bot(api_token=settings.BOT_TOKEN)


async def run_loop():
    # send updates
    checker = OrderChecker()
    await checker.check()
    asyncio.ensure_future(checker.periodic(), loop=loop)
    await bot.loop()


@bot.command(r'(/start|/help)')
async def start(chat: Chat, match):
    await chat.send_text(
        'Hello! I can notify you about your closed orders on next exchanges:\n'
        f'{get_supported_info()}\n'
        'Just send command like `/sub exchange_name api_key secret_key` (keys with read only permissions) '