import logging import ipaddress import json import paramiko import asyncssh from web3.auto import w3 from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage import config import addr_check_helper bot = Bot(token=config.bot_token) memory_storage = MemoryStorage() dp = Dispatcher(bot, storage=memory_storage) class MySSHClient(asyncssh.SSHClient): def validate_host_public_key(self, host, addr, port, key): return True class SetupStates(StatesGroup): waiting_for_server_address = State() waiting_for_server_login = State() waiting_for_server_password = State() waiting_for_wallet = State() waiting_for_wallet_password = State()
X, y = vectorizer.fit_transform( shuffle_df['abstract']), shuffle_df['citations'].apply( lambda x: multiclass(x)) clf = linear_model.LogisticRegression(class_weight='balanced', max_iter=10000) clf.fit(X, y) ######################################3 API_TOKEN = TOKEN # Configure logging logging.basicConfig(level=logging.INFO) # Initialize bot and dispatcher bot = Bot(token=API_TOKEN) # For example use simple MemoryStorage for Dispatcher. storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) # States class Form(StatesGroup): Classic = State() # Will be represented in storage as 'Form:Classic' Classic1 = State() # Will be represented in storage as 'Form:Classic1' ClassicB = State() # Will be represented in storage as 'Form:ClassicB' ClassicB1 = State() # Will be represented in storage as 'Form:ClassicB' DDF = State() # Will be represented in storage as 'Form:DDF' DDF1 = State() # Will be represented in storage as 'Form:DDF'
async def bot_fixture(event_loop): """ Bot fixture """ _bot = Bot(TOKEN, loop=event_loop, parse_mode=types.ParseMode.MARKDOWN) yield _bot await _bot.close()
sys.exit(1) BOT_TOKEN = os.getenv('BOT_TOKEN') HEROKU_APP_NAME = os.getenv('HEROKU_APP_NAME') # webhook settings WEBHOOK_HOST = f'https://{HEROKU_APP_NAME}.herokuapp.com' WEBHOOK_PATH = f'/webhook/{BOT_TOKEN}' WEBHOOK_URL = f'{WEBHOOK_HOST}{WEBHOOK_PATH}' # webserver settings WEBAPP_HOST = '0.0.0.0' WEBAPP_PORT = int(os.getenv('PORT')) bot = Bot(BOT_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) dp.middleware.setup(LoggingMiddleware()) # States of the finite state machine class BusinessLogic(StatesGroup): picture = State() colors = State() @dp.message_handler(commands=['help']) async def interface_description(message: types.Message): """Display of help information.""" await bot.send_message(chat_id=message.from_user.id, text='''
from starlette.requests import Request from starlette.routing import Route from starlette.responses import JSONResponse from starlette.middleware import Middleware from weebhook import set_weebhook from keyboard import board_1, board_2, board_3 from functions import parser, db_list, num_list, create_reply_keyboard, save_adm from config import TOKEN, MAIN_DB, ADMIN_DB client = MongoClient("localhost", 27017) db = client['NEW_DB'] new_collection = db[MAIN_DB] adm_collection = db[ADMIN_DB] bot = Bot(token=TOKEN) dp = Dispatcher(bot, storage=MongoStorage()) class States(Helper): mode = HelperMode.snake_case ADMIN = Item() DELETE = Item() FIO = Item() DOLJ = Item() ADRESS = Item() EMAIL = Item() PHONE = Item() CHANGE = Item() CHANGE_ROOM = Item() async def home(request: Request):
from functools import wraps from aiogram import Bot from aiogram import Dispatcher from aiogram import types from aiogram.utils.executor import start_polling from aiogram.types import ContentType, ChatType from aiogram.dispatcher.filters import Command, BoundFilter from aiogram.dispatcher import DEFAULT_RATE_LIMIT from aiogram.dispatcher.handler import CancelHandler, current_handler from aiogram.dispatcher.middlewares import BaseMiddleware from aiogram.utils.exceptions import Throttled from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.utils.markdown import escape_md logging.basicConfig(level=logging.INFO) bot: Bot = Bot(token="1548967936:AAGqYm37VMDR2B2WdxUk1NcuJLjoEkLH6cc") dp: Dispatcher = Dispatcher(bot=bot, storage=MemoryStorage()) def rate_limit(func, limit=2): @wraps(func) async def wrapper(*args, **kwargs): message = args[0] try: await dp.throttle("sticker", rate=limit) except Throttled as t: await message_throttled(message, t) return wrapper
import plistlib from hurry.filesize import size from aiogram import Bot from aiogram.types import Message, CallbackQuery from aiogram.dispatcher import Dispatcher from aiogram.utils import executor from aiogram.types.inline_keyboard import InlineKeyboardButton, InlineKeyboardMarkup from aiogram.types.reply_keyboard import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove from aiohttp import ClientSession from furl import furl from config import BOT_TOKEN # bot = Bot(token=BOT_TOKEN, proxy="socks5://163.172.152.192:1080") bot = Bot(token=BOT_TOKEN) dp = Dispatcher(bot) @dp.message_handler(commands=['start']) async def start(message: Message): await message.reply( 'Для начала работы пришлите боту ссылку вида https://appscloud.me/free_apps/app.php?id=<application_id>' ) async def get_plist_file(app_id: int) -> str: logger.info("Script started") async with ClientSession() as session: async with session.get( f"https://appscloud.me/free_apps/install.php?id={app_id}",
import logging import json from aiogram import Bot, Dispatcher, executor, types from models import User from defs import the_counter, get_msg, get_user, user_create, send import config as cfg logging.basicConfig(level=cfg.logging_level) bot = Bot(token=cfg.bot_token, parse_mode='html') dp = Dispatcher(bot) @dp.message_handler(commands=['start']) async def start(message: types.Message): if message.chat.type == 'private': text = ('Привет. В личном чате тебе доступна только команада ' '/balance.') await message.answer(text) @dp.message_handler(commands=['send']) async def send_cmd(message: types.Message): if message.chat.type == 'group'\ or message.chat.type == 'supergroup'\ and message.chat.id in cfg.aviable_chats: try: sum = int(message.text.split(' ')[1]) if message.reply_to_message:
import asyncio from aiogram import Bot, Dispatcher, executor, exceptions from scripts.db_manager import UsersDbManager from scripts.config import TOKEN, DEVELOPER_ID, ADMINS import scripts.markup as mk bot = Bot(TOKEN) dp = Dispatcher(bot) loop = asyncio.get_event_loop() @dp.message_handler(commands=['start']) async def start(message): tel_id = message.chat.id if not await UsersDbManager.user_exist(tel_id, loop): await UsersDbManager.add_user(tel_id, loop) await bot.send_message(tel_id, 'Выбери экзамен', disable_notification=True, reply_markup=mk.choose_exam()) @dp.message_handler(commands=['cancle']) async def cancel(message): tel_id = message.chat.id await UsersDbManager.update_context(tel_id, '0', loop) await bot.send_message(tel_id, 'Операция отменена') '''
from aiogram import Bot, Dispatcher, executor, types from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardRemove, \ ReplyKeyboardMarkup, KeyboardButton, \ InlineKeyboardMarkup, InlineKeyboardButton from helpers import * from getnews import sort_req from helpers_buttons import * from helpers_variables import * from config import * from cache import * from db import * from translations import * bot = Bot(token=API_TOKEN, proxy=PROXY, parse_mode="HTML") class change_current_settings: def __init__(self): pass # For callback query async def change_current(self, callback_query, dp): state = dp.current_state(user=callback_query.from_user.id) all_settings = {} _user_settings = { str(callback_query.from_user.id): { 'category': [], 'time_to_receive': [], 'language': [],
import os from myHelpers import createInlineMenu from handlers import contactsHandler as ch from handlers import gameHandler as gh from handlers import menuHandler as mh from handlers import resultHandler as rh from handlers import imageHandler as ih from aiogram import Bot, Dispatcher, executor, types from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardRemove, InputFile, ContentType logging.basicConfig(level=logging.INFO) bot = Bot(token=str(os.environ.get('TELEGRAM_TOKEN')), ) dp = Dispatcher(bot=bot) @dp.message_handler(content_types=ContentType.PHOTO) async def toPhoto(message: types.Message): await ih.imageHandler(message) @dp.message_handler(commands=['start']) async def printall(message: types.Message): await message.answer( 'Привет, я создан с целью помочь тебе поразвлечься и получить полезную информацию. Жмякай ниже и да начнется веселье!', reply_markup=createInlineMenu( [ # простая функция для создания клавиатуры (см. helpers.py)
uid = message.from_user.id log_str += '(' + str(uid) + '):\n' if(typ == 'text'): log_str += message.text + '\n' elif typ == 'files': log_str += "Отправил документ" elif typ == 'photos': log_str += "Отправил фото" log_str += updates_by_user[uid]['subject_name'] + "\n" return log_str #bot bot = Bot(token=API_TOKEN, parse_mode="HTML") disp = Dispatcher(bot) #data db_connection = sqlite3.connect("database.db") cur = db_connection.cursor() sg = SGClient() sg.login(SG_LOGIN, SG_PASSWORD) state = {} updates_by_user = {} del_subject_name = {} day = now().weekday() admins_id = [800155626] users_ids = [800155626, 664331079, 998445492, 912050293, 652242346, 723471766, 539584923, 1249475977,
import logging import config from aiogram import Bot, Dispatcher, executor, types import asyncio from connect import edit_bot bot = Bot(token=config.TOKEN_FORTUNETELLER) dp = Dispatcher(bot) logging.basicConfig(level=logging.INFO) side, num = 0, 0 Bot_fortuneteller = [ [ # 0, вступление ['Кто вы?', 'Я гадалка', 0], ['Здравствуйте. Позволите задать вам несколько вопросов?', 'Да', 1], ], [ # 1 ['Нет времени. Могу я вам задать несколько вопросов?', 'Да', 0], ['Не могу сказать, можем перейти к делу?', 'Да', 0], ], [ # 2 ['Скажите, знали ли вы Софию Хорову?»', 'Не могу точно сказать', 0], [ 'Вы моежете сказать, кто убил Софью Хорову?', 'Не могу точно сказать', 0 ],
import os from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from apiaudd.requests import MainRequests import read_env read_env.read_argv() var = os.environ.get TOKEN = var("BOT_TOKEN") bot = Bot(TOKEN, parse_mode="html") disp = Dispatcher(bot, storage=MemoryStorage()) APP_SPOT_URL = f"https://esc-ru.appspot.com/file/bot{TOKEN}/%s?host=api.telegram.org" audd = MainRequests(var("AUDD_TOKEN"), APP_SPOT_URL)
# APP logger logname_app = "app.log" handler_app = TimedRotatingFileHandler(filename=config['APP_logger']['path'] + logname_app, when="midnight", interval=1) handler_app.suffix = "%d%m%Y" handler_app.setLevel(log_level) formatter = logging.Formatter(log_format) handler_app.setFormatter(formatter) logger_app = logging.getLogger(__name__) logger_app.addHandler(handler_app) # P2P logger logname_p2p = "p2p.log" handler_p2p = TimedRotatingFileHandler(filename=config['P2P_logger']['path'] + logname_p2p, when="midnight", interval=1) handler_p2p.suffix = "%d%m%Y" handler_p2p.setLevel(log_level) formatter = logging.Formatter(log_format) handler_p2p.setFormatter(formatter) logger_p2p = logging.getLogger(__name__) logger_p2p.addHandler(handler_p2p) bot = Bot(token=config['BOT']['token'], parse_mode="HTML", proxy=config['PROXY']['url']) dp = Dispatcher(bot)
from aiogram import Bot from aiogram import Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from config import TOKEN from language_middleware import setup_middleware ####################### # Если у вас РКН блокирует запросы к Телеграму, можете перезаписать адрес по которому делаются запросы # И раскомментите следующие строки # from aiogram.bot import api # PATCHED_URL = "https://telegg.ru/orig/bot{token}/{method}" # setattr(api, "API_URL", PATCHED_URL) ####################### logging.basicConfig(format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s] %(message)s', level=logging.INFO) # loop = asyncio.get_event_loop() # Поток нам не нужен, т.к. он и так создается в диспатчере. storage = MemoryStorage() bot = Bot(token=TOKEN, parse_mode="HTML") dp = Dispatcher(bot, storage=storage) # Настроим i18n middleware для работы с многоязычностью i18n = setup_middleware(dp) # Создадим псевдоним для метода gettext _ = i18n.gettext
from aiogram import Bot, Dispatcher from data import config bot = Bot(token=config.BOT_TOKEN, parse_mode='HTML') dp = Dispatcher(bot)
import logging import config from aiogram import Bot, Dispatcher, executor, types logging.basicConfig(level=logging.INFO) bot = Bot(token=config.token) dp = Dispatcher(bot) @dp.message_handler(commands=["start"]) async def cmd_start(message: types.Message): poll_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) poll_keyboard.add( types.KeyboardButton(text="Начать тестирование", request_poll=types.KeyboardButtonPollType( type=types.PollType.QUIZ))) poll_keyboard.add(types.KeyboardButton(text="Отмена")) await message.answer("Нажмите на кнопку ниже для старта!", reply_markup=poll_keyboard) @dp.message_handler(lambda message: message.text == "Отмена") async def action_cancel(message: types.Message): remove_keyboard = types.ReplyKeyboardRemove() await message.answer( "Действие отменено. Введите /start, чтобы начать заново.", reply_markup=remove_keyboard) if __name__ == "__main__":
from aiogram import Bot, Dispatcher, executor, types from aiogram.contrib.fsm_storage.redis import RedisStorage 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)
""" Before running install aiogram, cool telegram bot-api wrapper """ from aioqiwi.wallet import Wallet, QiwiUpdate from aioqiwi.utils import BeautifulSum from aiogram import Bot, Dispatcher, types from aiogram.utils import markdown ME = 124191486 # your telegram user id qiwi = Wallet("qiwiToken") bot = Bot("telegramBotToken", parse_mode="markdown") disp = Dispatcher(bot) @qiwi.on_update(incoming=True) async def new_payment(event: QiwiUpdate): payment = event.Payment text = f":D Woop-woop! {payment.account} sent you {BeautifulSum(payment.Sum).humanize}\n" text += f"Commentary: {payment.comment}" if payment.comment else "" await bot.send_message(ME, text) @disp.message_handler(commands=["send"], prefix="./!") @disp.message_handler(regexp=r"^.send \d*\.?\d* (\(?\+?[0-9]*\)?)?[0-9_\- \(\)] .*") async def send_money(event: types.Message): # process text with pattern: .send amount_float receiver_phone_number comments cmd, amount, peer, comment = event.text.split(maxsplit=3)
import logging import config from aiogram import Bot, Dispatcher, executor, types from sqlite import DataBase import asyncio bot = Bot(token=config.TOKEN) dp = Dispatcher(bot) logging.basicConfig(level=logging.INFO) bd = DataBase('data/user.db') bd.clear() # очищаем бд # приветственное слово @dp.message_handler(commands=['start']) async def hi(message: types.Message): await message.answer( 'Привет! Добро пожаловать. Следи за игрой и успевай отправлять ответы') # обработка сообщений @dp.message_handler(content_types=['text']) async def said(message: types.Message): if '1' != message.text and '2' != message.text and '3' != message.text: await message.answer('Такого варианта ответа нет') elif not bd.check_id(message.from_user.id): bd.new_user( message.from_user.id, message.text) # заносим id в бд для защиты от спама ответов
import config import logging import asyncio from datetime import datetime from aiogram import Bot, Dispatcher, executor, types from sqlighter import SQLighter from stopgame import StopGame # задаем уровень логов logging.basicConfig(level=logging.INFO) # инициализируем бота bot = Bot(token=config.API_TOKEN) dp = Dispatcher(bot) # инициализируем соединение с БД db = SQLighter('db.db') # инициализируем парсер sg = StopGame('lastkey.txt') # Команда активации подписки @dp.message_handler(commands=['subscribe']) async def subscribe(message: types.Message): if (not db.subscriber_exists(message.from_user.id)): # если юзера нет в базе, добавляем его db.add_subscriber(message.from_user.id) else:
from aiogram.utils.markdown import text, bold, italic, code, pre from aiogram.types import ParseMode, InputMediaPhoto, InputMediaVideo, ChatActions from apscheduler.schedulers.asyncio import AsyncIOScheduler from config import TOKEN from config import PROXY_URL # from config import TOKEN_DIALOGFLOW # Create log string logging.basicConfig( format= u'%(filename)s [ LINE:%(lineno)+3s ]#%(levelname)+8s [%(asctime)s] %(message)s', level=logging.INFO) # pass to bot token and proxy url bot = Bot(token=TOKEN, proxy=PROXY_URL) # bot = Bot(token=TOKEN) dp = Dispatcher(bot) def get_weather(arr): answer = '' for i in arr: owm = pyowm.OWM('70732ac514bf006244ac74c5f31de5aa', language='ru') town = i obs = owm.weather_at_place(town) weather = obs.get_weather() temp = weather.get_temperature('celsius')['temp'] temp = round(temp) wind = weather.get_wind()['speed'] wind = round(wind)
# webhook config TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN') WEBHOOK_HOST = os.environ.get('HOST') WEBHOOK_URL_PATH = '/webhook' + '/' + TELEGRAM_TOKEN WEBHOOK_URL = f"https://{WEBHOOK_HOST}{WEBHOOK_URL_PATH}" # set logging settings log = logging.getLogger(__name__) logging.config.dictConfig(settings['logging']) # aio debug aio_debug = settings.get('asyncio_debug_enabled', False) if aio_debug is True: loop.set_debug(True) bot = Bot(TELEGRAM_TOKEN, loop=loop) dispatcher = Dispatcher(bot, storage=MemoryStorage()) async def init_pg(app): engine = await aiopg.sa.create_engine(dsn=os.environ.get('DATABASE_URL'), loop=app.loop) app['db'] = engine async def close_pg(app): app['db'].close() await app['db'].wait_closed() async def on_shutdown(app, url=None):
import asyncio from aiogram import Bot, Dispatcher, executor, types from googlesearch import search from core import db_helper from core.config import API_TOKEN # initialize bot & dispatcher bot = Bot(API_TOKEN) dp = Dispatcher(bot) # response templates about = '''Asynchronous Google search Telegram bot built on \ <code>aiogram</code> & <code>googlesearch</code>. GitHub repo: <a href='https://github.com/fleischgewehr/gsearch_tgbot'>here</a>''' current_settings = '''Your settings: - Language: {0} - Safe search: {1} Choose an option:''' # results are stored here results = [] @dp.message_handler(commands=['start']) async def welcome(message):
from aiogram import Bot, Dispatcher, types from aiogram.contrib.fsm_storage.redis import RedisStorage from aiohttp import web from constants import config bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML) storage = RedisStorage() dp = Dispatcher(bot, storage=storage) routes = web.RouteTableDef()
import os from aiogram import Bot, Dispatcher, executor, types, utils from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage WEBHOOK = True WEBHOOK_HOST = c.app # heroku app url WEBHOOK_PATH = '/webhook/' WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}" WEBAPP_HOST = '0.0.0.0' WEBAPP_PORT = os.environ.get('PORT') bot = Bot(c.token) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Activate(StatesGroup): code = State() class Export(StatesGroup): code = State() class Delete(StatesGroup): code = State()
from data import token from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage bot = Bot(token) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage)
async def _register_manager(self, after_break=False, ignore_token_checks=False) -> None: # Get info about user to use it in this class me = await self._client.get_me() self._me = me.id self._name = get_display_name(me) if not ignore_token_checks: # Assert that token is set to valid, and if not, # set `init_complete` to `False` and return is_token_asserted = await self._assert_token() if not is_token_asserted: self.init_complete = False return # We successfully asserted token, so set `init_complete` to `True` self.init_complete = True # Create bot instance and dispatcher self.bot = Bot(token=self._token) self._bot = self.bot # This is a temporary alias so the # developers can adapt their code self._dp = Dispatcher(self.bot) # Get bot username to call inline queries try: self.bot_username = (await self.bot.get_me()).username self._bot_username = self.bot_username # This is a temporary alias so the # developers can adapt their code except Unauthorized: logger.critical("Token expired, revoking...") return await self._dp_revoke_token(False) # Start the bot in case it can send you messages try: m = await self._client.send_message(self.bot_username, "/start") except (InputUserDeactivatedError, ValueError): self._db.set("geektg.inline", "bot_token", None) self._token = False if not after_break: return await self._register_manager(True) self.init_complete = False return False except Exception: self.init_complete = False logger.critical("Initialization of inline manager failed!") logger.exception("due to") return False await self._client.delete_messages(self.bot_username, m) # Register required event handlers inside aiogram self._dp.register_inline_handler(self._inline_handler, lambda inline_query: True) self._dp.register_callback_query_handler(self._callback_query_handler, lambda query: True) self._dp.register_chosen_inline_handler( self._chosen_inline_handler, lambda chosen_inline_query: True) self._dp.register_message_handler(self._message_handler, lambda *args: True, content_types=["any"]) old = self.bot.get_updates revoke = self._dp_revoke_token async def new(*args, **kwargs): nonlocal revoke, old try: return await old(*args, **kwargs) except aiogram.utils.exceptions.TerminatedByOtherGetUpdates: await revoke() except aiogram.utils.exceptions.Unauthorized: logger.critical("Got Unauthorized") await self._stop() self.bot.get_updates = new # Start polling as the separate task, just in case we will need # to force stop this coro. It should be cancelled only by `stop` # because it stops the bot from getting updates self._task = asyncio.ensure_future(self._dp.start_polling()) self._cleaner_task = asyncio.ensure_future(self._cleaner())
import asyncio import logging import random from typing import Dict from aiogram import Bot, types from aiogram.contrib.fsm_storage.redis import RedisStorage from aiogram.dispatcher import Dispatcher, FSMContext import config logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() bot = Bot(token=config.API_TOKEN, loop=loop) storage = RedisStorage() dp = Dispatcher(bot, storage=storage) ADMIN_ID = 211270198 def check_admin(message): return message.chat.id in {ADMIN_ID} def format_participants(participants: Dict) -> str: return '\n'.join( '{name} ({id}): {bonus}'.format(name=p[0], id=id, bonus=p[1]) for id, p in participants.items())