示例#1
21
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.redis import RedisStorage
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from os import getenv
import logging

debug = getenv('DEBUG', 'false').lower()
if debug not in ['true', 'false']:
    raise RuntimeError('Unknown debug state')
debug = True if debug == 'true' else False
if debug:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

bot = Bot(getenv('TG_TOKEN'))

storage_type = getenv('STORAGE_TYPE', 'memory').lower()
if storage_type == 'memory':
    storage = MemoryStorage()
elif storage_type == 'redis':
    storage = RedisStorage(host=getenv('REDIS_HOST', 'localhost'),
                           port=int(getenv('REDIS_PORT', '6379')),
                           db=int(getenv('REDIS_STORAGE_DB', 2)),
                           password=None if getenv('REDIS_PASSWORD', None)
                           == '' else getenv('REDIS_PASSWORD', None))
else:
    raise RuntimeError('Unknown storage')

dp = Dispatcher(bot, storage=storage)
示例#2
0
async def main():
    logger.error('Starting bot')
    config = load_config('bot.ini')

    if config.tg_bot.use_redis:
        storage = RedisStorage()
    else:
        storage = MemoryStorage()

    loop = asyncio.get_event_loop()
    pool = await create_pool(
        user=config.db.user,
        password=config.db.password,
        database=config.db.database,
        host=config.db.host,
        loop=loop,
    )

    bot = Bot(token=config.tg_bot.token)
    dp = Dispatcher(bot, storage=storage)
    dp.middleware.setup(DbMiddleware(pool))
    dp.middleware.setup(RoleMiddleware(config.tg_bot.admin_id))
    dp.filters_factory.bind(RoleFilter)
    dp.filters_factory.bind(AdminFilter)

    register_admin(dp)
    register_user(dp)

    # start
    try:
        await dp.start_polling()
    finally:
        await bot.close()
示例#3
0
async def main():
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    )
    logger.error("Starting bot")
    config = load_config("bot.ini")

    if config.tg_bot.use_redis:
        storage = RedisStorage()
    else:
        storage = MemoryStorage()
    pool = await create_pool(
        user=config.db.user,
        password=config.db.password,
        database=config.db.database,
        host=config.db.host,
        echo=False,
    )

    bot = Bot(token=config.tg_bot.token)
    dp = Dispatcher(bot, storage=storage)
    dp.middleware.setup(DbMiddleware(pool))
    dp.middleware.setup(RoleMiddleware(config.tg_bot.admin_id))
    dp.filters_factory.bind(RoleFilter)
    dp.filters_factory.bind(AdminFilter)

    register_admin(dp)
    register_user(dp)

    # start
    try:
        await dp.start_polling()
    finally:
        await bot.close()
示例#4
0
    def __init__(
            self,
            redis_host,
            redis_port,
            redis_db,
            redis_password,
            config:
        TelegramBotServiceConfig = default_telegram_bot_service_config,
            loop: Optional[asyncio.AbstractEventLoop] = None):
        self._config = config
        self.loop = loop or asyncio.get_event_loop()
        self.redis_host = redis_host
        self.redis_port = int(redis_port)
        self.redis_db = int(redis_db)
        self.redis_password = redis_password
        self._storage = RedisStorage(host=self.redis_host,
                                     port=self.redis_port,
                                     db=self.redis_db,
                                     password=self.redis_password)

        self._bot = Bot(token=self._config.token,
                        proxy=self._config.proxy,
                        loop=self.loop)
        self._dispatcher = Dispatcher(self._bot,
                                      loop=self.loop,
                                      storage=self._storage)
        self._executor = Executor(self._dispatcher,
                                  skip_updates=True,
                                  loop=self.loop)
示例#5
0
async def redis_store(redis_options):
    s = RedisStorage(**redis_options)
    try:
        yield s
    finally:
        conn = await s.redis()
        await conn.execute('FLUSHDB')
        await s.close()
        await s.wait_closed()
示例#6
0
async def redis_store(redis_options):
    if int(aioredis.__version__.split(".")[0]) == 2:
        pytest.skip('aioredis v2 is not supported.')
        return
    s = RedisStorage(**redis_options)
    try:
        yield s
    finally:
        conn = await s.redis()
        await conn.execute('FLUSHDB')
        await s.close()
        await s.wait_closed()
示例#7
0
from utils import UserStates, ListItem
from messages import MESSAGES

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

config = configparser.ConfigParser()
config.read('config.ini')
key = config['API KEYS']['bot_api_key']

bot = Bot(token=key)
dp = Dispatcher(bot, storage=RedisStorage())
dp.middleware.setup(LoggingMiddleware())
# ========================================= Config Sections ===========================================================#


@dp.message_handler(state='*', commands=['start'])
async def start(message: types.Message.from_user.id):
    print('14151515')
    # print(f'id = {id}')
    # if database.User.objects(user_id=user_id).frist():
    #     User(user_id)
    #
    # elif not database.User.objects(user_id=user_id).frist():
    #     await message.reply(MESSAGES['wait_for_name_msg'], reply_markup=InlineKB('main_menu').generate_kb(),
    #                         reply=False, parse_mode=ParseMode.HTML)
示例#8
0
import logging

from aiogram import Bot, Dispatcher
from aiogram import types
from aiogram.contrib.fsm_storage.redis import RedisStorage

import config
import handlers

logging.basicConfig(level=logging.INFO)
storage = RedisStorage(config.REDIS_HOST,
                       config.REDIS_PORT,
                       db=config.REDIS_DB,
                       password=config.REDIS_PASS)
bot = Bot(token=config.API_TOKEN, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot, storage=storage)
handlers.user.setup(dp)
示例#9
0
import logging
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.redis import RedisStorage
from config.config import TOKEN, redis_pass
import aioredis

storage = RedisStorage("redis", 6379)
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=storage)
logging.basicConfig(level=logging.INFO)
示例#10
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_old

# 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
示例#11
0
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.redis import RedisStorage
from utils.db_api.db_gino import db
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from data import config

bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = RedisStorage(config.REDIS_IP, 6379, db=1)
dp = Dispatcher(bot, storage=storage)
scheduler = AsyncIOScheduler()

__all__ = ["bot", "storage", "dp", "db", "scheduler"]
示例#12
0
from gcc_app.constants import BAD_WORDS_FILE
from gcc_app.global_utils import ReaderTXT

db = declarative_base()


async def create_async_session():
    engine = create_async_engine(SQLALCHEMY_DATABASE_URI, echo=True)
    async_session = sessionmaker(engine,
                                 expire_on_commit=False,
                                 class_=AsyncSession)
    return async_session()


storage = RedisStorage(**REDIS_URI)

calendar = GoogleCalendar(EMAIL_GOOGLE_CALENDAR)

bot = Bot(token=TOKEN_BOT)
dp = Dispatcher(bot, storage=storage)
dp.middleware.setup(LoggingMiddleware())

BAD_WORDS = ReaderTXT(BAD_WORDS_FILE).read_txt_into_frozenset()


async def set_commands(bot: Bot):
    commands = [
        BotCommand(command=COMMAND_CREATE_EVENT[0],
                   description=COMMAND_CREATE_EVENT[1]),
        BotCommand(command=COMMAND_HELP[0], description=COMMAND_HELP[1]),
示例#13
0
    TELEGRAM_BOT_WEBHOOK_ENDPOINT: str = "https://coinpush666.herokuapp.com"
    REDIS_URL: str = "redis://:pcb97fb88ac53b92fc063ce9261657c6d9409316b3b9c8b867a935b57a6f52783@ec2-54-172-142-101.compute-1.amazonaws.com:9800"
    CACHE_TTL: int = 60 * 59
    PROXY: str = 'http://127.0.0.1:7890'
    DEFAULT_TIMEZONE: str = "Asia/Shanghai"
    DO_RELEASE: bool = False
    DATABASE_URL: str = 'postgres://*****:*****@ec2-52-0-114-209.compute-1.amazonaws.com:5432/df00t1odivmjt3'

    @property
    def is_production(self):
        return self.ENV == "production"


settings = Settings()

if settings.REDIS_URL:
    redis_config = RedisConfig(settings.REDIS_URL)
    dispatcher_storage = RedisStorage(host=redis_config.host,
                                      port=redis_config.port,
                                      password=redis_config.password)
    aio_lru_cache_partial = partial(cached,
                                    cache=Cache.REDIS,
                                    endpoint=redis_config.host,
                                    port=redis_config.port,
                                    password=redis_config.password)
    aio_lru_cache_1h = aio_lru_cache_partial(ttl=settings.CACHE_TTL)

else:
    dispatcher_storage = MemoryStorage()
    aio_lru_cache_partial = partial(cached)
    aio_lru_cache_1h = aio_lru_cache_partial(ttl=settings.CACHE_TTL)
示例#14
0
from aiogram import types
from aiogram.bot.bot import Bot
from aiogram.contrib.fsm_storage.redis import RedisStorage
from aiogram.dispatcher.dispatcher import Dispatcher

from config import Config

bot = Bot(token=Config.api_token, parse_mode=types.ParseMode.HTML)
storage = RedisStorage(db=5)
dp = Dispatcher(bot, storage=storage)
示例#15
0
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.redis import RedisStorage
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from data import config
from utils.misc.parser import Parser
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG)

parser = Parser('rasp.xlsx')
rasp = parser.get_rasp()
old_file_id = ['0']
bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = RedisStorage(host='rediska')
# storage = RedisStorage()
dp = Dispatcher(bot, storage=storage)
scheduler = AsyncIOScheduler()
示例#16
0
import logging
import sqlite3
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.redis import RedisStorage


con = sqlite3.connect('web/app/app/db/project.db')

API_TOKEN = ''
with open('token.txt', 'r') as f:
    API_TOKEN = f.readline()


# Configure logging
logging.basicConfig(filename='debug.log',
                    filemode='a',
                    format='%(asctime)s, %(name)s %(levelname)s %(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.DEBUG)

# Initialize bot and dispatcher
storage = RedisStorage('localhost', 6379, db=1)

# storage = MemoryStorage()
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot, storage=storage)

con.execute('SELECT * FROM jobs WHERE id = 20').fetchone()
示例#17
0
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import FSMContext
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

from inliner import Inliner
from utils import TestStates
from tasker import Jsoner
from dedoder import Decoder
import redis
import asyncio

logging.basicConfig(level=logging.INFO)

bot = Bot(token='1160891964:AAE0ba37vkpS14RQlH0VVlI2VPTovdS_D7U')

dp = Dispatcher(bot, storage=RedisStorage('localhost', 6379, db=5))
dp.middleware.setup(LoggingMiddleware())

r = redis.Redis(db=5)

button_task = KeyboardButton('Назначить задачу')

markup = ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(button_task)

# TABLE = { 'users': {}}
# json_file = json.dumps(TABLE, indent=4)
# r.hset('TABLE', 'table', json_file)


@dp.message_handler(state=None, commands='start')
示例#18
0
import logging

from aiogram import Dispatcher, Bot, types
from aiogram.contrib.fsm_storage.redis import RedisStorage
from docs.config import REDIS, BOT_TOKEN

logger = logging.getLogger(__name__)
bot = Bot(token=BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = RedisStorage(db=REDIS.get('DB'),
                       host=REDIS.get('HOST'),
                       port=REDIS.get('PORT'))
dp = Dispatcher(bot, storage=storage)
示例#19
0
import asyncio
from pathlib import Path

from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.redis import RedisStorage
from aiogram.utils.executor import Executor
from loguru import logger

import config

ROOT_DIR: Path = Path(__file__).parent.parent

loop = asyncio.get_event_loop()
storage = RedisStorage(host=config.REDIS_HOST, port=config.REDIS_PORT)

bot = Bot(token=config.TELEGRAM_BOT_TOKEN, loop=loop, parse_mode='HTML')
dp = Dispatcher(bot=bot, loop=loop, storage=storage)

executor = Executor(dp, skip_updates=True)


async def setup():
    user = await bot.me
    logger.info(f"Bot: {user.full_name} [@{user.username}]")
    logger.debug(f'{ROOT_DIR=}')