示例#1
0
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.redis import RedisStorage2
from loguru import logger

from app import config

bot = Bot(config.TELEGRAM_TOKEN, parse_mode=types.ParseMode.HTML)
storage = RedisStorage2(host=config.REDIS_HOST,
                        port=config.REDIS_PORT,
                        db=config.REDIS_DB_FSM)
dp = Dispatcher(bot, storage=storage)


def setup():
    from app import filters
    from app import middlewares
    from app.utils import executor

    middlewares.setup(dp)
    filters.setup(dp)
    executor.setup()

    logger.info("Configure handlers...")
    # noinspection PyUnresolvedReferences
    import app.handlers
示例#2
0
import os, logging
from aiogram import Bot, Dispatcher, executor, types

# Get token from TOKEN.txt file (create it if not existent)
with open(os.path.dirname(os.path.realpath(__file__)) + '/TOKEN.txt') as file:
    TOKEN = file.readline().strip()

# Bot and Dispatcher definition
bot = Bot(token=TOKEN)
dispatcher = Dispatcher(bot)

# Set logging for error handling format
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)


# Pray command
@dispatcher.message_handler(commands=['pray'])
async def send_pray(message: types.Message):
    await message.answer(
        text='In nome del Padre, del Figlio e della scarpetta con il ragù')


# Poll command
@dispatcher.message_handler(commands=['poll'])
async def send_poll(message: types.Message):
    options = [
        '11.45', '12.00', '12.15', '12.30', '12.45', '13.00', '13.15',
        'Ho il mio cibo', 'Oggi non vengo'
    ]
示例#3
0
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.types import ParseMode
from aiogram.utils.executor import Executor
import sentry_sdk

from core import config
from core.packages import PackagesLoader
from mixpanel import Mixpanel

logging.basicConfig(level=logging.INFO)

log = logging.getLogger('assistant')

loop = asyncio.get_event_loop()

bot = Bot(config.bot_token, parse_mode=ParseMode.HTML, validate_token=False)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage, loop=loop)
runner = Executor(dp, skip_updates=config.skip_updates)

loader = PackagesLoader()

dp.middleware.setup(LoggingMiddleware('bot'))

mp = Mixpanel(config.mixpanel_key)

if config.sentry_url:
    sentry_sdk.init(config.sentry_url)
示例#4
0
import asyncio
import logging

from aiogram import Bot, Dispatcher, types
from aiogram.utils import exceptions, executor

API_TOKEN = 'BOT TOKEN HERE'

logging.basicConfig(level=logging.INFO)
log = logging.getLogger('broadcast')

loop = asyncio.get_event_loop()
bot = Bot(token=API_TOKEN, loop=loop, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot, loop=loop)


def get_users():
    """
    Return users list

    In this example returns some random ID's
    """
    yield from (61043901, 78238238, 78378343, 98765431, 12345678)


async def send_message(user_id: int,
                       text: str,
                       disable_notification: bool = False) -> bool:
    """
    Safe messages sender
示例#5
0
import logging
import redis

# указываем какие переменные окружения используем
API_TOKEN = os.getenv("API_TOKEN")
REDIS_DB = os.getenv("REDIS_DB")
USER_ID = int(os.getenv("USER_ID"))

# подключаемся к Redis, как к базе данных, для подгрузки баланса кошелька
r = redis.StrictRedis(REDIS_DB, db=0)

# задаем уровень логов
logging.basicConfig(level=logging.INFO)

# определяем бота Telegram
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

# описываем клавиатуру ReplyKeyboardMarkup
item_eth = types.KeyboardButton('ETH')
item_pht = types.KeyboardButton('PHT')
item_vin = types.KeyboardButton('VIN')
item_all = types.KeyboardButton('ALL')
markup = types.ReplyKeyboardMarkup(
    keyboard=[[item_eth, item_pht, item_vin, item_all]], resize_keyboard=True)


def auth_custom(func):
    """
    Функция-декоратор для того, чтобы ботом мог пользоваться только один юзер, его id указываем в переменных
    окружения, другой пользователь не сможет узнать баланс чужого кошелька.
示例#6
0
from aiogram.utils.markdown import link
from utils.htmlprocessing import get_name_for_url, get_url_of_face_with_id
from utils.findface import get_face_descriptor

AIOGRAM_API_TOKEN = os.getenv('AIOGRAM_API_TOKEN')

logging.basicConfig(level=logging.INFO)
# Настройки nmslib
index = nmslib.init(method='hnsw',
                    space='l2',
                    data_type=nmslib.DataType.DENSE_VECTOR)
index.loadIndex('embeddings.bin')
query_time_params = {'efSearch': 400}
index.setQueryTimeParams(query_time_params)
# Настройки aiogram
bot = Bot(token=AIOGRAM_API_TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    await message.reply("Hi!\nI'm FindCloneBot!\n" +
                        "Help you find people's by photo.\n" +
                        "Just send me photo and i'll try to find.")


@dp.message_handler()
async def echo_message(message: types.Message):
    await message.reply("I can't undersand you!\n" +
                        "If you need help, send me /help \n" +
                        "Or just send me photo!")
示例#7
0

#telegram bot

#token='915096497:AAFvPSbMpvjdtNSucGNwSy6afA8UURu89nI'




#testbot

token = '1225831912:AAG60sUGFoeRVePSufgLFM0Xaat176T2t1o'



bot = Bot(token)

dp = Dispatcher(bot)
db = SQLighter('db.db')

inline_btn_1 = InlineKeyboardButton('4🕓', callback_data='time4')
inline_btn_2 = InlineKeyboardButton('5🕔', callback_data='time5')
inline_btn_3 = InlineKeyboardButton('6🕕', callback_data='time6')
inline_btn_4 = InlineKeyboardButton('7🕖', callback_data='time7')
inline_btn_5 = InlineKeyboardButton('8🕗', callback_data='time8')
inline_btn_6 = InlineKeyboardButton('9🕘', callback_data='time9')
inline_btn_7 = InlineKeyboardButton('10🕙', callback_data='time10')
inline_btn_8 = InlineKeyboardButton('11🕚', callback_data='time11')
inline_btn_9 = InlineKeyboardButton('12🕛', callback_data='time12')
inline_kb1 = InlineKeyboardMarkup().add(inline_btn_1, inline_btn_2, inline_btn_3, inline_btn_4, inline_btn_5, inline_btn_6, inline_btn_7, inline_btn_8, inline_btn_9)
示例#8
0
文件: core.py 项目: icYFTL/EzGen
from aiogram import Bot
from aiogram.dispatcher import Dispatcher
import json
import logging
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from source.database import Base

logging.basicConfig(
    filename='logs/telegram.log',
    level=logging.INFO,
    format='%(asctime)-15s | [%(name)s] %(levelname)s => %(message)s')

config = json.load(open('config.json', 'r', encoding='UTF-8'))
text = config['msg']

engine = create_engine(f'sqlite:///{config["db_name"]}', echo=False)
Base.metadata.create_all(engine, checkfirst=True)

Session = sessionmaker(bind=engine)

bot = Bot(token=config['tg_token'])
dp = Dispatcher(bot)
示例#9
0
API_TOKEN = 'BOT TOKEN HERE'

# webhook settings
WEBHOOK_HOST = 'https://your.domain'
WEBHOOK_PATH = '/path/to/api'
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"

# webserver settings
WEBAPP_HOST = 'localhost'  # or ip
WEBAPP_PORT = 3001

logging.basicConfig(level=logging.INFO)

loop = asyncio.get_event_loop()
bot = Bot(token=API_TOKEN, loop=loop)
dp = Dispatcher(bot)


@dp.message_handler()
async def echo(message: types.Message):
    await bot.send_message(message.chat.id, message.text)


async def on_startup(dp):
    await bot.set_webhook(WEBHOOK_URL)
    # insert code here to run it after start
    #


async def on_shutdown(dp):
示例#10
0
from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor

bot = Bot(token='***')
dp = Dispatcher(bot)


@dp.message_handler()
async def get_mes(message: types.Message):

    chat_id = message.chat.id
    send = await bot.send_message(chat_id=chat_id, text='asdasd')
    print(send.to_python())


executor.start_polling(dp)
示例#11
0
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
import django
django.setup()
from db.models import *
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

import aiogram
import asyncio
from aiogram import types, executor
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters import CommandHelp, CommandStart
from config import BOT_TOKEN
from handlers import *

bot = Bot(BOT_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


@dp.message_handler(commands=['db'])
async def db_cmd(message: types.Message):
    await db_handler(message)


@dp.message_handler(commands=['start'])
async def start_cmd(message: types.Message):
    await start_handler(message)


@dp.message_handler(content_types=["new_chat_members"])
示例#12
0
import aiohttp
import logging
import ssl

import weather, chatbot
from aiogram import Bot, Dispatcher, executor, types
from config import API_TOKEN

PROXY_URL = 'http://127.0.0.1:8001'

# 配置日志
logging.basicConfig(level=logging.INFO)

# 初始化机器人和调度器

bot = Bot(API_TOKEN, proxy=PROXY_URL)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    """
    这个函数将会被回调,当客户端输入'/start'或者'/help'命令时
    """
    await message.reply("欢迎来到jacklov3的垃圾机器人\n,请问有什么可以帮助您的吗?")


@dp.message_handler(commands=['weather'])
async def re_weather(message: types.Message):
    if len(message.text) == 8:
        await message.reply('你的用法好像有问题,应该是/weather 北京')
#!venv/bin/python
# TODO: Make CAPITALIZATION configurable

import config
import logging
from aiogram import Bot, Dispatcher, executor, types
from xkcdpass import xkcd_password as xp
import random
import dbworker
from utils import get_language
from texts import strings

bot = Bot(token=config.token, parse_mode="HTML")
dp = Dispatcher(bot)
logging.basicConfig(level=logging.INFO)


def make_settings_keyboard_for_user(user_id, lang_code):
    """
    Prepare keyboard for user based on his settings

    :param user_id: User ID in Telegram
    :return: Inline Keyboard object
    """
    user = dbworker.get_person(user_id)
    kb = types.InlineKeyboardMarkup()

    wrds_lst = []
    if user["word_count"] >= (config.length_min + 1):
        wrds_lst.append(
            types.InlineKeyboardButton(text=strings.get(
示例#14
0
import asyncio
import os
import logging
import datetime

from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
from poem_for_the_day.poem import get_poem_today
from aiogram.types import ParseMode
from poem_for_the_day.db import init_pg, close_pg, get_user
from poem_for_the_day.db import users

bot = Bot(token=os.environ['TOKEN'])
dp = Dispatcher(bot)

db = dict()
loop = asyncio.get_event_loop()


@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    data = {
        'id': message.from_user.id,
        'username': message.from_user.username,
        'first_name': message.from_user.first_name,
        'last_name': message.from_user.last_name,
        'time': None
    }

    await add_user(data)
示例#15
0
import asyncio
import logging

from aiogram import Bot
from aiogram import Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage

from config import TOKEN
from sql import create_pool

# from aiogram.contrib.fsm_storage.redis import RedisStorage2

logging.basicConfig(format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s]  %(message)s',
                    level=logging.INFO)
loop = asyncio.get_event_loop()

# Set up storage (either in Redis or Memory)
storage = MemoryStorage()

bot = Bot(token=TOKEN, parse_mode="HTML")
dp = Dispatcher(bot, storage=storage)

db = loop.run_until_complete(create_pool())
示例#16
0
from aiogram import Bot, types
from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, \
    InlineKeyboardMarkup, InlineKeyboardButton, ChatActions, ParseMode
import aiogram.utils.markdown as md
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext, Dispatcher
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils import executor

logging.basicConfig(
    format=
    u'%(filename)s [ LINE:%(lineno)+3s ]#%(levelname)+8s [%(asctime)s]  %(message)s',
    level=logging.INFO)

bot = Bot(token=config.TOKEN)
base_url = config.BASE_URL
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)

SOHO = 'AgACAgIAAxkBAAEFxk1fPXHvhAt9D14IrAS1HLCcYR4hmQACErAxG1aA6EllJDonIGgcqdteC5cuAAMBAAMCAAN5AAM_OgACGwQ'
DRINK = 'AgACAgIAAxkBAAEFxk1fPXHvhAt9D14IrAS1HLCcYR4hmQACErAxG1aA6EllJDonIGgcqdteC5cuAAMBAAMCAAN5AAM_OgACGwQ'
TEA = 'AgACAgIAAxkBAAEFxk1fPXHvhAt9D14IrAS1HLCcYR4hmQACErAxG1aA6EllJDonIGgcqdteC5cuAAMBAAMCAAN5AAM_OgACGwQ'
FOOD = 'AgACAgIAAxkBAAEFxk1fPXHvhAt9D14IrAS1HLCcYR4hmQACErAxG1aA6EllJDonIGgcqdteC5cuAAMBAAMCAAN5AAM_OgACGwQ'
VIDEO_STOCKS = 'BAACAgIAAxkBAAEFxjJfPWcAAXNMPn35cwlm4oNGL4bluoYAAn4MAAJn_vBJG9n8U7HsiocbBA'


@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    greet_kb = ReplyKeyboardMarkup(resize_keyboard=True,
                                   one_time_keyboard=True)
示例#17
0
'''
Main application module
'''


from datetime import datetime
from aiogram import Bot, Dispatcher, executor, types
from googleapiclient.discovery import build
import config

youtube = build('youtube', 'v3', developerKey=config.API_KEY)

bot = Bot(token=config.BOT_TOKEN)
bot_dispatcher = Dispatcher(bot)

last_update = None
videos = {}


@bot_dispatcher.message_handler(commands=['start'])
async def welcome_handler(message: types.Message):
    '''Sends welcome message on /start command'''
    await message.reply(config.WELCOME_MESSAGE)


@bot_dispatcher.message_handler(commands=['help'])
async def help_handler(message: types.Message):
    '''Sends help message on /help command'''
    await message.reply(config.HELP_MESSAGE)

from aiogram import Bot, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import Dispatcher
from aiogram.dispatcher.webhook import SendMessage
from aiogram.utils.executor import start_webhook

bot_token = '1205352313:AAHvh4X2cpF5TJCa2pTXb_YNORFvKyVzjb4'

webhook_host = 'https://challenge.teachwizard.ru' 
webhook_path = '/api/'
webhook_url = f"{webhook_host}{webhook_path}"

webapp_host = 'localhost'
webapp_port = 3001

bot = Bot(token=bot_token)
dp = Dispatcher(bot)

@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    """
    This handler will be called when user sends `/start` or `/help` command
    """
    await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")
    
@dp.message_handler()
async def echo(message: types.Message):
    # old style:
    # await bot.send_message(message.chat.id, message.text)

    await message.answer(message.text)
示例#19
0
import asyncio
from aiogram import Dispatcher, Bot, executor, types
from config import BOT_TOKEN
from aiogram.contrib.fsm_storage.memory import MemoryStorage

from middlewares.ThrottlingMiddleware import ThrottlingMiddleware

loop = asyncio.get_event_loop()
bot = Bot(BOT_TOKEN, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot, loop=loop, storage=MemoryStorage())

if __name__ == "__main__":
    from handlers import dp
    dp.middleware.setup(ThrottlingMiddleware())
    executor.start_polling(dp, skip_updates=True)
示例#20
0
import logging
import datetime
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.types.reply_keyboard import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton
from aiogram.utils.markdown import text, bold, italic, code, pre  # markdown utils
from aiogram.types import ParseMode as PM  # to send text in markdown

from dict import lessons_top, lessons_down, lsn_emoji, lsn_time

# Initialize bot and dispatcher
bot = Bot(token='YOUR_TELEGRAM_BOT_TOKEN')
dp = Dispatcher(bot, storage=MemoryStorage())

# Configure logging
logging.basicConfig(format=u'%(filename)+13s [ LINE:%(lineno)-4s] %(levelname)-8s [%(asctime)s] %(message)s',
					level=logging.INFO, filename="schedule.log")

dp.middleware.setup(LoggingMiddleware())

ADMIN_ID = []


def create_inline_keyboard(day):
	inline_keyboard = InlineKeyboardMarkup()

	btns = []
	days_ukr = ['пн', 'вт', 'ср', 'чт', 'пт']
	days_query = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
from aiogram import Bot, Dispatcher, types
from aiogram.utils.executor import start_polling
from pymorphy2 import MorphAnalyzer

from converter_bot.converter import MassVolumeConverter
from converter_bot.measurements import Measurements
from converter_bot.message_parser import MessageParser

PROXY_URL = "http://34.253.177.131:3128"
API_TOKEN = os.environ.get("API_KEY")

logging.basicConfig(level=logging.INFO)

DEBUG = os.environ.get("DEBUG")
if DEBUG:
    bot = Bot(token=API_TOKEN, proxy=PROXY_URL)
else:
    bot = Bot(token=API_TOKEN)

dp = Dispatcher(bot)

measurements = Measurements()
message_parser = MessageParser('ru')
converter = MassVolumeConverter(measurements)
morph = MorphAnalyzer()


def is_correct_message(message: types.Message):
    return re.match(r"^\d+[,.]?\d*\s+[\w\s]+>[\w\s]+$", message.text)

示例#22
0
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.files import JSONStorage
from excel_worker import ExcelBook
import os

TOKEN = os.getenv('BOT_TOKEN1')
bot = Bot(TOKEN, parse_mode='Html')
storage = JSONStorage('storage/storage.json')
dp = Dispatcher(bot, storage=storage)
excel_book = ExcelBook('storage/Учет закупок.xlsx')
示例#23
0
import logging
import os
from aiogram import Bot, Dispatcher, executor, types

logging.basicConfig(level=logging.INFO)

bot = Bot(token=os.getenv('INFO_TECH_NEWS_BOT_TOKEN'))
dp = Dispatcher(bot)


@dp.message_handler(commands='news')
async def echo(message: types.Message):
    with open('collected_data.txt', 'r') as f:
        news = f.readlines()

    news = ''.join(news)
    await message.answer(news)


if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)
示例#24
0
import logging
import os
from aiogram import types, Bot
from decouple import config

from messages_controller import extract_user_object, extract_message_object, extract_chat_object
from controllers.glpi import glpi
from controllers.zabbix import zabbix
from controllers.validation import validation
from database.connection import Database

bot = Bot(token=config('API_TOKEN'), parse_mode="markdown")


class BeltisBot:
    def __init__(self, dispatcher):
        self.dispatcher = dispatcher
        self.bot_name = "Beltis TI bot"
        self.bot_description = "*AINDA EM PRODUÇÃO*"
        self.bot = bot
        self.get_version()
        self.connections = {"glpi": False, "zabbix": False, "database": False}
        self.connect()
        self.validation = validation(self)
        self.run_bot()

    def get_version(self):
        path = os.path.join(
            os.path.split(os.path.dirname(__file__))[0], 'version')
        version = open(path, 'r').read()
        self.version = version
示例#25
0
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage

import config

bot = Bot(token=config.Bot_token, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot=bot, storage=storage)
示例#26
0
# Instructions: https://core.telegram.org/bots/self-signed
WEBHOOK_SSL_CERT = './webhook_cert.pem'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = './webhook_pkey.pem'  # Path to the ssl private key

WEBHOOK_URL = f"https://{WEBHOOK_HOST}:{WEBHOOK_PORT}{WEBHOOK_URL_PATH}"

# Web app settings:
#   Use LAN address to listen webhooks
#   User any available port in range from 1024 to 49151 if you're using proxy, or WEBHOOK_PORT if you're using direct webhook handling
WEBAPP_HOST = 'localhost'
WEBAPP_PORT = 3001

BAD_CONTENT = ContentTypes.PHOTO & ContentTypes.DOCUMENT & ContentTypes.STICKER & ContentTypes.AUDIO

loop = asyncio.get_event_loop()
bot = Bot(TOKEN, loop=loop)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


async def cmd_start(message: types.Message):
    # Yep. aiogram allows to respond into webhook.
    # https://core.telegram.org/bots/api#making-requests-when-getting-updates
    return SendMessage(chat_id=message.chat.id,
                       text='Hi from webhook!',
                       reply_to_message_id=message.message_id)


async def cmd_about(message: types.Message):
    # In this function markdown utils are userd for formatting message text
    return SendMessage(message.chat.id,
示例#27
0
import aiogram
from aiogram import Bot, Dispatcher, executor, types
import test
import config
import datetime
import pytz
import json
import logging

logging.basicConfig(level=logging.INFO)

PY_TIMEZONE = pytz.timezone(config.TIMEZONE)
TIMEZONE_SN = config.TIMEZONE_SN

bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
    await message.answer('Greetings! I can show you exchange rates.\n' +
                         'To get the exchange rates press /list.\n' +
                         'To get some help press /help')


@dp.message_handler(commands=['help'])
async def help_command(message: types.Message):
    keyboard = aiogram.types.InlineKeyboardMarkup()
    keyboard.add(
        aiogram.types.InlineKeyboardButton(text='My tg :)',
                                           url='https://t.me/Hvidahorn'))
示例#28
0
async def bot_fixture():
    """ Bot fixture """
    _bot = Bot(TOKEN)
    yield _bot
    await (await _bot.get_session()).close()
示例#29
0
文件: loader.py 项目: Na3aga/gmbot
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage

import config

bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
示例#30
0
REDIS_COMM = CONFIG["basic"]["redis_conn"]
REDIS_PORT = CONFIG["basic"]["redis_port"]
TOKEN = CONFIG["basic"]["bot_token"]
NAME = TOKEN.split(':')[0] + CONFIG["advanced"]["bot_name_additional"]

# Init MongoDB
mongodb = MongoClient(MONGO_CONN).sophie

# Init Redis
redis = redis.StrictRedis(host=REDIS_COMM,
                          port=REDIS_PORT,
                          db='1',
                          decode_responses=True)

tbot = TelegramClient(NAME, API_ID, API_HASH)

# Telethon
tbot.start(bot_token=TOKEN)

# AIOGram
bot = Bot(token=TOKEN, parse_mode=types.ParseMode.HTML)
storage = RedisStorage()
dp = Dispatcher(bot, storage=storage)

# Flask
flask = Flask(__name__)

bot_info = asyncio.get_event_loop().run_until_complete(bot.get_me())
BOT_USERNAME = bot_info.username  # bot_info.username
BOT_ID = bot_info.id