コード例 #1
0
def telegram_mode(watcher: WatcherManager, config: Configuration):
    """Run the telegram bot

    Args:
        watcher (WatcherManager): A WatcherManager object, used to manage the watching of urls
        config (Configuration): A python representation of the config file on the disk
    """
    bot = Bot(watcher, config.token, config.password, config.tick_frequency)
    bot.run_bot()
コード例 #2
0
def process_bot_notifications(bot: Bot, listings: List[Listing]) -> None:
    bot_terms = bot.get_terms()
    all_results: Dict[str, List[Listing]] = defaultdict(list)
    for listing in listings:
        for term in bot_terms:
            lower_term = term.lower()
            if lower_term in listing.full_json['title'].lower(
            ) or lower_term in listing.model.lower(
            ) or lower_term in listing.make.lower(
            ) or lower_term in listing.full_json['description'].lower():
                all_results[term].append(listing)

    for term, listings in all_results.items():
        strings = list(
            map(
                lambda lst:
                f"[{lst.full_json['title']}]({lst.full_json['_links']['web']['href']})",
                listings))
        bot.send_update(term, strings)
コード例 #3
0
import sys

import requests

from telegram_bot import Bot

EKB_ID = '1486209'
W_TOKEN = '93c5495ecda2427c3e8852c732d9b84c'
try:
    t_token = sys.argv[1]
    bot = Bot(t_token, W_TOKEN, EKB_ID)
    bot.run()
except requests.exceptions.RequestException:
    print(
        'Ошибка доступа к серверам телеграма. Вероятно вы предварительно не запустили VPN :)'
    )
except Exception as e:
    print(
        'Укажите корректный токен телеграм бота (без скобок): python3 start_bot.py <TOKEN>'
    )
コード例 #4
0
def start(bot_token: str):
    logger = create_logger("start")
    logger.debug("Start bot")

    updater = Updater(token=bot_token, use_context=True)
    bot = Bot(updater)

    dispatcher = updater.dispatcher

    logger.debug("Register command handlers")
    # CommandHandler
    dispatcher.add_handler(CommandHandler("users", bot.show_users))
    dispatcher.add_handler(
        CommandHandler("users_to_annoy", bot.annoy_users_list))

    # chat_admin
    dispatcher.add_handler(CommandHandler("delete_chat", bot.delete_chat))
    dispatcher.add_handler(CommandHandler("get_data", bot.get_data))
    dispatcher.add_handler(CommandHandler("mute", bot.mute, pass_args=True))
    dispatcher.add_handler(CommandHandler("unmute", bot.unmute,
                                          pass_args=True))
    dispatcher.add_handler(CommandHandler("kick", bot.kick, pass_args=True))

    # Debugging
    dispatcher.add_handler(CommandHandler("status", bot.status))
    dispatcher.add_handler(CommandHandler("server_time", bot.server_time))
    dispatcher.add_handler(CommandHandler("version", bot.version))

    # MessageHandler
    dispatcher.add_handler(
        MessageHandler(Filters.command, bot.handle_unknown_command))
    dispatcher.add_handler(MessageHandler(Filters.all, bot.handle_message))
    dispatcher.add_handler(
        MessageHandler(Filters.status_update.left_chat_member,
                       bot.handle_left_chat_member))
    dispatcher.add_handler(
        MessageHandler(Filters.status_update.new_chat_members, bot.new_member))

    # ErrorHandler
    dispatcher.add_error_handler(
        lambda _bot, _update, error: handle_telegram_error(error))

    state_file = "state.json"
    logger.debug(f"Read state from {state_file}")
    if os.path.exists(state_file):
        with open(state_file) as file:
            try:
                state = json.load(file)
            except json.decoder.JSONDecodeError as e:
                logger.warning(f"Unable to load previous state: {e}")
                state = {}

        bot.set_state(state)

    try:
        if sys.argv[1] == "--testrun":
            logger.info("Scheduling exit in 5 seconds")

            def _exit():
                logger.info("Exiting")
                updater.stop()
                updater.is_idle = False

            timer = threading.Timer(5, _exit)
            timer.setDaemon(True)
            timer.start()
    except IndexError:
        pass

    logger.info("Running")
    updater.start_polling()
    updater.idle()
コード例 #5
0
    'Accept-Version': '3.0',
    'Authorization': 'Bearer ' + str(REVERB_API_CODE),
    'Content-Type': 'application/hal+json'
}

insert_query = """
    INSERT INTO reverb_guitar_data.listing (id, make, model, year, condition, price_cents, currency, offers_enabled, thumbnail, full_json) VALUES %s
"""

conn = psycopg2.connect(
    f'dbname={PG_DB} user={PG_USER} password={PG_PASS} port={PG_PORT} host={PG_HOST}'
)
conn.autocommit = True
cur = conn.cursor()

bot = Bot(str(os.getenv('TELEGRAM_TOKEN')))

sched = BlockingScheduler()


class Listing():
    def __init__(self, values):
        self.full_json: Dict = values

        self.id: int = int(values['id'])
        self.make: str = values['make']
        self.model: str = values['model']
        self.year: str = values['year']
        self.condition: str = values['condition']['display_name']
        self.price_cents: int = values['buyer_price']['amount_cents']
        self.currency: str = values['buyer_price']['currency']
コード例 #6
0
def bot_processor(delay):
    global lock, db
    bot = Bot(db["token"], admin_id=db["admin_id"])
    while True:
        lock.acquire()
        messages = bot.get_last_messages()
        for message in messages:
            if round(time.time()) - message["date"] <= db["max_time_diff"]:
                try:
                    incoming_message = {
                        "text": message["text"],
                        "chat_id": message["chat"]["id"]
                    }
                # some messages have not text (stickers, files etc)
                except:
                    continue
                outgoing_message = message_handler(incoming_message)
                if outgoing_message is None:
                    continue
                elif outgoing_message["method"] == "send_message":
                    bot.send_message(outgoing_message["chat_id"],
                                     outgoing_message["text"])
                elif outgoing_message["method"] == "send_location":
                    bot.send_location(outgoing_message["chat_id"],
                                      outgoing_message["coordinates"])
                elif outgoing_message["method"] == "send_photo":
                    bot.send_file(outgoing_message["chat_id"],
                                  outgoing_message["photo"], "photo",
                                  outgoing_message["caption"])
                elif outgoing_message["method"] == "send_audio":
                    bot.send_file(outgoing_message["chat_id"],
                                  outgoing_message["audio"], "audio")
                elif outgoing_message["method"] == "send_document":
                    if outgoing_message["caption"].startswith("Log"):
                        if outgoing_message["chat_id"] == bot.admin_id:
                            bot.send_file(bot.admin_id,
                                          open(bot.log_file, "rb"), "document",
                                          outgoing_message["caption"])
                        else:
                            bot.send_message(
                                bot.admin_id,
                                "Unresolved attempt to access to log file from {}"
                                .format(outgoing_message["chat_id"]))
                    else:
                        pass
        db["last_checked_update_id"] = bot.last_checked_update_id
        db.write()
        lock.release()
        time.sleep(delay)
コード例 #7
0
from telegram.update import Update

from functools import wraps

from secrets import bot_token
from telegram_bot import Bot

T = TypeVar('T')
U = TypeVar('U')

logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG)

updater = Updater(token=bot_token)
dispatcher = updater.dispatcher
bot = Bot()
bot_commands: list[Callable[[], None]] = []


def add_context(func: Callable[[], None]) -> Callable[[Update, CallbackContext], None]:
    """Decorator to automatically use the bot in the appropriate update and context in command callbacks, without
    having to worry about specifying them each time as arguments."""

    @wraps(func)
    def decorator(update: Update, context: CallbackContext):
        bot.init(update, context)
        return func()

    return decorator