def send_photo(bot: TeleBot,
               bot_state: BotState,
               message: Message,
               database: DataBase,
               ydisk: YandexDisk,
               is_canceled: bool = False):
    state_additional = bot_state.get_state(message.from_user.id)["additional"]
    keyboard = None
    if is_canceled:
        keyboard = state_additional["keyboard"]["with_cancel"]
    else:
        keyboard = state_additional["keyboard"]["normal"]
    photo = database.get_random_photos(1)
    if len(photo) > 0:
        photo = photo[0]
        photo_url = ydisk.disk.get_download_link(photo["filepath"])
        bot.send_photo(message.chat.id,
                       photo_url,
                       reply_markup=keyboard,
                       caption="https://www.instagram.com/{}".format(
                           photo["source"]))
    else:
        bot.send_message(
            message.chat.id,
            "Фотографии закончились :(\nВведите /help, остановите эту хреновину."
        )
        bot_state.add_state(message.chat.id, "help")

    return photo
def echo(bot: TeleBot, bot_state: BotState, message: Message,
         database: DataBase, ydisk: YandexDisk):
    state_additional = bot_state.get_state(message.from_user.id)["additional"]
    last_photo = state_additional["last_photo"]
    # state_additional["penult_photo"] =
    if message.text == "Подтвердить":
        database.set_photo_status(last_photo["hash"], "checked",
                                  message.from_user.id)
        state_additional["penult_photo"] = last_photo
        state_additional["last_photo"] = send_photo(bot, bot_state, message,
                                                    database, ydisk, True)
    elif message.text == "Удалить":
        database.set_photo_status(last_photo["hash"], "deleted",
                                  message.from_user.id)
        state_additional["penult_photo"] = last_photo
        state_additional["last_photo"] = send_photo(bot, bot_state, message,
                                                    database, ydisk, True)
    elif message.text == "Отменить последнее решение":
        database.set_photo_status(state_additional["penult_photo"]["hash"],
                                  "unchecked", message.from_user.id)
        send_canceled_photo(state_additional["penult_photo"], bot, bot_state,
                            message, ydisk)
        state_additional["last_photo"] = state_additional["penult_photo"]
    else:
        bot.send_message(
            message.chat.id,
            "Введите нормальный ответ или воспользуйтесь другой командой (/help), чтобы отменить действие этой."
        )
Example #3
0
 def __init__(self, host, port, nick):
     self.state = BotState()
     self.state._host = host
     self.state._port = port
     self.state._nick = nick
     
     self._command = BotCommands()
     self._is_connected = False
def end(bot: TeleBot, bot_state: BotState, message: Message,
        database: DataBase, ydisk: YandexDisk):
    print("{}: ended photo validation".format(message.from_user.username))
    state_additional = bot_state.get_state(message.from_user.id)["additional"]
    state_additional["keyboard"]["normal"] = ReplyKeyboardRemove()
    state_additional["keyboard"]["with_cancel"] = ReplyKeyboardRemove()
    bot.send_message(message.chat.id,
                     "Подождите немного. Выполняются изменения...",
                     reply_markup=ReplyKeyboardRemove())
    photos_for_deleting = database.get_photos_for_deleting(
        message.from_user.id)
    for photo in photos_for_deleting:
        if ydisk.disk.exists(photo["filepath"]):
            ydisk.disk.remove(photo["filepath"])
        if photo["source"] is not None:
            database.increment_insta_stat(photo["source"], "unapproved_photos")
        database.delete_photo(photo["hash"])
    bot.send_message(message.chat.id, "Ваши правки применены.")
Example #5
0
 def _activate_bot(self, serviceName):
     '''Gets bot state. Starts it if not yet running.'''
     # check if bot running
     try:
         bot = self.activeBots[serviceName]
     except KeyError:
         # ask container for bot acls
         acls = self.access.on_service_acls(self.session, serviceName)
         # build a bot state object
         bot = BotState(serviceName, uuid.uuid4().hex, acls)
         # decide if tracking sync or not now
         self.needsSync |= (acls & ACL_SERVICE_SYNC)
         # ask container if any additional params for service
         appData = self.access.on_service_config(self.session, serviceName)
         # launch the bot because not started
         self.launcher.start_service(bot.serviceName, bot.token,
                                     self.manager, appData)
         # store bot state for future lookup
         self.activeBots[serviceName] = bot
     return bot
def do(bot: TeleBot, bot_state: BotState, message: Message, database: DataBase,
       ydisk: YandexDisk):
    bot.send_message(
        message.chat.id,
        "Начата проверка фотографий. Чтобы закончить проверку, введите любую другую команду (/help)."
    )
    print("{}: started photo validation".format(message.from_user.username))
    state_additional = bot_state.get_state(message.from_user.id)["additional"]

    keyboard1 = ReplyKeyboardMarkup(resize_keyboard=True)
    keyboard1.row("Подтвердить", "Удалить")
    keyboard1.row("Отменить последнее решение")
    keyboard2 = ReplyKeyboardMarkup(resize_keyboard=True)
    keyboard2.row("Подтвердить", "Удалить")
    state_additional["keyboard"] = {
        "with_cancel": keyboard1,
        "normal": keyboard2
    }
    photo = send_photo(bot, bot_state, message, database, ydisk)

    state_additional["last_photo"] = photo
Example #7
0
import time

import telebot

from availablecommands import commands
from botstate import BotState
from database import DataBase
from yandexdisk import YandexDisk
from mthreading import mult_threading
import schedule
from commands.publish import send_photos

database = DataBase()
ydisk = YandexDisk(token=os.environ["YADISKTOKEN"])
bot = telebot.TeleBot(os.environ['TOKEN'])
bot_state = BotState(saved_commands=commands.get_na_commands())


@mult_threading
def time_publish():
    # schedule.every().day.at("20:00").do(send_photos, bot, database, ydisk, 10)
    schedule.every(2).hours.do(send_photos, bot, database, ydisk, 1)
    while True:
        schedule.run_pending()
        time.sleep(1)


@bot.message_handler(content_types=["text"])
def answer_commands(message):
    try:
        global bot_state
def send_canceled_photo(photo, bot: TeleBot, bot_state: BotState,
                        message: Message, ydisk: YandexDisk):
    state_additional = bot_state.get_state(message.from_user.id)["additional"]
    keyboard = state_additional["keyboard"]["normal"]
    photo_url = ydisk.disk.get_download_link(photo["filepath"])
    bot.send_photo(message.chat.id, photo_url, reply_markup=keyboard)
Example #9
0
class Boteco:

    def __init__(self, host, port, nick):
        self.state = BotState()
        self.state._host = host
        self.state._port = port
        self.state._nick = nick
        
        self._command = BotCommands()
        self._is_connected = False

    def connect(self):
        if self._is_connected:
            return

        self._sock = Connection()
        self._sock.connect(self.state._host, self.state._port)
        
        while 1:
            data = self._read_line()
            if data == "":
                break
                
            print(data)

        self._send_command("NICK " + self.state._nick)
        self._send_command("USER " + self.state._nick + " myhost myhost :" + self.state._nick)

        # Read the whole MOTD and whatever else there is and simply ignore
        while 1:
            data = self._read_line()
            if data == "":
                return
                
            print(data)

    def get_socket(self):
        return self._sock

    def join_channel(self, channel):
        self._command.join(channel)
      
    def is_connected(self):
        return self._sock.is_connected

    def parse(self, data):
        ircmsg = IRCMessage(data)

        if ircmsg.msg_type == "":
            return

        if ircmsg.msg_type == "PING":
            self._send_command("PONG " + ircmsg.from_host)
            
        elif ircmsg.msg_type == "ERROR":
            self._sock.disconnect()

        elif ircmsg.msg_type == "JOIN":
            self._handle_join(ircmsg)

        elif ircmsg.msg_type == "PRIVMSG":
            self._handle_privmsg(ircmsg)


    def _read_line(self):
        return self._sock.read_line()

    def _send_command(self, command):
        self._command.send_command(command)

    def _send_message(self, to, msg):
        self._command.send_message(to, msg)

    def _handle_privmsg(self, ircmsg):
        if ircmsg.cmd == "":
            return

        self._command.execute(ircmsg)

    # TODO: Might want to rewrite this...
    def _handle_join(self, ircmsg):

        # Is it the bot joining?
        if ircmsg.from_nick == self.state._nick:
            people_on_channel = []
            joined_channel = ircmsg.to
            
            while 1:
                data = self._read_line()
                print(data)
                
                tokens = [el.strip() for el in data.split(" ")]

                if tokens[1] == "353":
                    for i in tokens[5:]:
                        people_on_channel.append(i.strip(":"))
                        self.state.joined_channel(ircmsg.to, i.strip(":"))

                        print("Joined channel %s\n" % ircmsg.to)
                    
                elif tokens[1] == "366":
                    # End of names, we are done reading data
                    break


            print("Joined channel %s" % joined_channel)
            for i in people_on_channel:
                print("Person %s is on channel" % i)

            print("End of JOIN")
    
        else:
            self.state.joined_channel(ircmsg.to, ircmsg.from_nick)