Ejemplo n.º 1
0
    def darkroom(self, bot, update):
        printlog(update, "darkroom")

        _, chat_id = get_ids(update)
        count_and_write(self.db, update, "commands")

        try:
            with urlopen("https://ttkamerat.fi/darkroom/api/v1/sensors/latest"
                         ) as url:
                sensor_data = json.loads(url.read().decode())

                value_light = 0
                isDarkroomPopulated = False

                # JSON härössä muodossa, sen takia teemme näin. Esimerkki:
                #   {"entries": [{"value": 191, "sensor": "light1", "inserted": "2018-07-27T16:18:43.589Z"}]}
                for sensor in sensor_data["entries"]:
                    if sensor["sensor"] == "light1":
                        value_light = sensor["value"]

                if value_light > 100:
                    isDarkroomPopulated = True

                if isDarkroomPopulated:
                    reply = "Joku on pimiöllä :O\n"
                else:
                    reply = "Pimiö tyhjä :(\n"

                bot.send_message(chat_id=chat_id, text=reply)
        except URLError as e:
            print(e.reason)
            bot.send_message(chat_id=chat_id,
                             text="Ei ny onnistunu (%s)" % e.reason)
Ejemplo n.º 2
0
    def add_blacklist(self, bot, update):
        printlog(update, "blacklist")

        user_id, _ = get_ids(update)

        if (update.message.chat.type != "private"):
            update.message.reply_text("Ole hyvä ja lähetä tämä pyyntö yksityisviestillä.\n" \
                                    "Please send this request via private message.")
            return

        if self.db.in_blacklist(user_id):
            update.message.reply_text("Tietosi on jo poistettu, eikä sinua seurata.\n" \
                                    "Your information is already deleted and you are not tracked.")
            return

        keyboard = [[
            InlineKeyboardButton("Ei (No)", callback_data="false"),
            InlineKeyboardButton("Kyllä (Yes)", callback_data="true")
        ]]

        reply_markup = InlineKeyboardMarkup(keyboard)

        update.message.reply_text("Haluatko, että kaikki henkilöivät tietosi poistetaan Markun tietokannasta," \
                                "ja käyttäjäsi lisätään \"älä seuraa\"-listalle?\n\n" \
                                "Do you want to delete all of your personifiable information from Markku's database" \
                                "and add your user to the \"do not track\" list?",
                                reply_markup=reply_markup)
Ejemplo n.º 3
0
    def start(self, bot, update):
        printlog(update, "start")

        _, chat_id = get_ids(update)  # Ignoraa user_id, tätä käytetään paljon
        count_and_write(self.db, update, "commands")

        bot.send_message(chat_id=chat_id, text="Woof woof")
Ejemplo n.º 4
0
def parse_and_count(db, update):
    user_id, chat_id = get_ids(update)

    # Älä laske blacklistattuja
    if db.in_blacklist(user_id):
        return

    text = update.message.text.upper()

    # usernameksi laitetaan 'Not found' jos sitä ei ole
    username = "******"
    if update.message.from_user.username is not None:
        username = update.message.from_user.username

    # chat titleksi laitetaan 'Private' jos sitä ei ole (priva chätti)
    chat_title = "Private"
    if update.message.chat.title is not None:
        chat_title = update.message.chat.title

    # muuttaa kaikki paitsi kirjaimet ja numerot välilyönneiksi
    parsed_text = re.sub('[^a-zA-Z0-9 öÖäÄ\n]', ' ', text)

    # splittaa välilyöntien kohdalta
    split_text = parsed_text.split(" ")

    # poistaa listasta yhden ja nollan pituiset alkiot
    split_text = [i for i in split_text if len(i) > 1]

    # laskee listasta sanat ja tallentaa sen muotoon {"sana1": sanaMäärä1, "sana2": sanaMäärä2 ... }
    wordCount = Counter(split_text)

    # lisätään sanat db:n sanacountteriin
    for word in wordCount:
        db.word_collection_add(user_id, chat_id, chat_title, username, word,
                               wordCount[word])
Ejemplo n.º 5
0
    def camera_versus(self, bot, update):
        printlog(update, "camera versus")

        _, chat_id = get_ids(update)
        count_and_write(self.db, update, "commands")

        msg = camera_versus_text()
        bot.send_message(chat_id=chat_id, text=msg)
Ejemplo n.º 6
0
    def protip(self, bot, update):
        printlog(update, "protip")

        _, chat_id = get_ids(update)
        count_and_write(self.db, update, "commands")

        protip_list = masterlist.tips

        protip_index = random.randint(0, len(protip_list) - 1)

        bot.send_message(chat_id=chat_id, text=protip_list[protip_index])
Ejemplo n.º 7
0
    def protip(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        protip_list = masterlist.tips

        protip_index = random.randint(0, len(protip_list) - 1)

        bot.send_message(chat_id=chat_id, text=protip_list[protip_index])
Ejemplo n.º 8
0
def count_and_write(db, update, var):
    user_id, chat_id = get_ids(update)

    # TODO: tsekkaa onko nimi Not Found, tsekkaa onko käyttäjänimi muuttunu järkeväks, jos on niin päivitä
    username = "******"
    if update.message.from_user.username is not None:
        username = update.message.from_user.username

    # Älä laske blacklistattuja
    if db.in_blacklist(user_id):
        return

    db.increment_counter(user_id, chat_id, var, 1)
Ejemplo n.º 9
0
    def darkroom(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return
        
        try:
            with urlopen(environ["SENSOR_API_ADDRESS"]) as url:
                sensor_data = json.loads(url.read().decode())

                value_light = 0
                insert_time = ""

                # JSON härössä muodossa, sen takia teemme näin. Esimerkki:
                #   {"entries": [{"value": 191, "sensor": "light1", "inserted": "2018-07-27T16:18:43.589Z"}]}

                if len(sensor_data["entries"]) != 0:
                    for sensor in sensor_data["entries"]:
                        if sensor["sensor"] == "light1":
                            value_light = sensor["value"]
                            insert_time = sensor["inserted"]

                    if value_light > 100:
                        reply = "Joku on pimiöllä :O"
                    else:
                        reply = "Pimiö tyhjä :("

                    # Selvitetään kuinka vanhaa uusin tieto on. Palvelimen data UTC:na, verrataan lokaaliin aikaan.
                    # Tällä toteutuksella lokaalin aikavyöhykkeen ei pitäisi haitata.
                    current_datetime = datetime.now()
                    now_timestamp = time.time()

                    offset = datetime.fromtimestamp(now_timestamp) - datetime.utcfromtimestamp(now_timestamp)

                    inserted_datetime = datetime.strptime(insert_time, "%Y-%m-%dT%H:%M:%S.%fZ") + offset

                    date_diff = current_datetime - inserted_datetime

                    if date_diff.seconds > 3600 and date_diff.days == 0:
                        reply += " ({} tuntia sitten)".format(date_diff.seconds//3600)
                    elif date_diff.days != 0:
                        reply += " ({} päivää ja {} tuntia sitten)".format(date_diff.days, date_diff.seconds//3600)

                else:
                    reply = "Ei tietoa :/"

                bot.send_message(chat_id=chat_id, text=reply)
        except URLError as e:
            print(e.reason)
            bot.send_message(chat_id=chat_id, text="Ei ny onnistunu (%s)" % e.reason)
Ejemplo n.º 10
0
    def route_command(self, bot, update, command, args):
        printlog(update, command)

        username = update.message.from_user.username
        chat_title = update.message.chat.title
        user_id, chat_id = get_ids(update)

        if username is not None:
            self.db.update_name(user_id, username)

        if chat_title is not None:
            self.db.update_name(chat_id, chat_title)

        if command in self.commands:
            self.commands[command](bot, update)
Ejemplo n.º 11
0
    def noutaja(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        url = "https://dog.ceo/api/breed/retriever/golden/images/random"

        req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

        with urlopen(req) as page:
            retriever_data = json.loads(page.read().decode())

            picture_link = retriever_data["message"]

            bot.sendPhoto(chat_id=chat_id, photo=picture_link)
Ejemplo n.º 12
0
    def noutaja(self, bot, update):
        printlog(update, "noutaja")

        _, chat_id = get_ids(update)
        count_and_write(self.db, update, "commands")

        url = "https://dog.ceo/api/breed/retriever/golden/images/random"

        req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

        with urlopen(req) as page:
            retriever_data = json.loads(page.read().decode())

            picture_link = retriever_data["message"]

            bot.sendPhoto(chat_id=chat_id, photo=picture_link)
Ejemplo n.º 13
0
    def remove_blacklist(self, bot, update, args):
        user_id, _ = get_ids(update)

        if (update.message.chat.type != "private"):
            update.message.reply_text("Ole hyvä ja lähetä tämä pyyntö yksityisviestillä\n" \
                                    "Please send this request via private message")
            return

        if self.db.in_blacklist(user_id):
            
            self.db.remove_blacklist(user_id)
            update.message.reply_text("Markku seuraa sinua taas.\n" \
                                    "Markku is tracking you again.\n\n" \
                                    "*sniff sniff* Woof!")
        else:
            update.message.reply_text("Et ole Markun \"älä seuraa\"-listalla.\n" \
                                    "You are not on Markku's \"do not track\" list.")
Ejemplo n.º 14
0
    def stats(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        if self.db.in_blacklist(user_id):
            update.message.reply_text("Markku ei seuraa sinua. Käytä komentoa /unblacklist , jos haluat seurannan käyttöön.\n" \
                                    "Markku does not track you. Use the command /unblacklist to enable tracking.")
            return

        counters = self.db.get_counters()

        user_counters = {}
        counter_sum = 0

        # Haetaan käyttäjän laskurien arvot databaseltä
        for i in counters:
            user_counters[i] = self.db.get_counter_user(user_id, chat_id, i)
            if i != "kiitos":
                counter_sum += user_counters[i]

        # Muodostetaan lähetettävä viesti
        msg = "@{}<code>:".format(update.message.from_user.username)
        msg += "\n{:<10}{:>5}".format("Total:", counter_sum)

        for counter in user_counters:
            if counter == "kiitos":
                if user_counters["messages"] != 0:
                    msg += "\n└ {}% Kiitosta".format(
                        round(
                            user_counters[counter] /
                            user_counters["messages"] * 100, 1))
                else:
                    msg += "\n└ ??% Kiitosta"

            else:
                msg += "\n{:<10}{:>5} ({:>4}%)".format(
                    counter.capitalize() + ":", user_counters[counter],
                    round(user_counters[counter] / counter_sum * 100, 1))

        msg += "</code>"

        # Lähetetään viesti. parse_mode mahdollistaa html-muotoilun viestissä
        bot.send_message(chat_id=chat_id, text=msg, parse_mode='HTML')
Ejemplo n.º 15
0
    def darkroom(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        try:
            with urlopen(environ["SENSOR_API_ADDRESS"]) as url:
                sensor_data = json.loads(url.read().decode())

                # JSON härössä muodossa, sen takia teemme näin. Esimerkki:
                #   {"entries": [{"value": 191, "sensor": "light1", "inserted": "2018-07-27T16:18:43.589Z"}]}

                if len(sensor_data["entries"]) != 0:

                    light_message = ""
                    voice_message = ""

                    for sensor in sensor_data["entries"]:
                        sensor_entry = CommandRouter.handle_sensor(sensor)
                        if sensor_entry.name() == "light1":
                            light_message = CommandRouter.get_light_message(
                                sensor_entry)
                        elif sensor_entry.name() == "voice1":
                            voice_message = CommandRouter.get_voice_message(
                                sensor_entry)

                    if not light_message:
                        light_message = "Can't reach darkroom 🤔"
                    if not voice_message:
                        voice_message = "Can't reach virtual darkroom 🤔"

                    reply = f"{light_message}.\n{voice_message}."

                else:
                    reply = "🤷‍♂️"

            bot.send_message(chat_id=chat_id, text=reply)
        except URLError as e:
            print(e.reason)
            bot.send_message(chat_id=chat_id,
                             text="Ei ny onnistunu (%s)" % e.reason)
Ejemplo n.º 16
0
    def help(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        reply = "Komennot:\n" \
                "/darkroom - Kertoo onko joku pimiöllä.\n" \
                "/stats - Chattikohtaiset statsit.\n" \
                "/topten <i>laskuri</i> - Paljastaa chatin spämmibotit.\n"\
                "/noutaja - Postaa satunnaisen noutajakuvan.\n"\
                "/protip - Antaa ammatti valo kuvaus vinkin!\n"\
                "/blacklist - Poistaa lähettäjän datat tietokannasta ja estää uusien tallentamisen.\n"\
                "/unblacklist - Sallii omien tietojen tallentamisen blacklist-komennon jälkeen.\n"\
                "\n" \
                "Botin koodit: @eltsu7, @kulmajaba ja @anttimoi\n" \
                "https://github.com/eltsu7/MarkkuBot\n" \
                "Valosensorit ja siihen koodit: @anttimoi"

        bot.send_message(chat_id=chat_id, text=reply, parse_mode='HTML')            
Ejemplo n.º 17
0
    def msg_text(self, bot, update):
        printlog(update, "text")

        _, chat_id = get_ids(update)
        count_and_write(self.db, update, "messages")

        sticker_list = masterlist.stickers
        message = update.message.text.lower()

        parse_and_count(self.db, update)

        lotto = random.randint(1, 201)

        if "kiitos" in message:
            count_and_write(self.db, update, "kiitos")

            if lotto < 11:
                update.message.reply_text("Kiitos")
            elif lotto < 16:
                sticker_index = random.randint(0, len(sticker_list) - 1)
                bot.send_sticker(chat_id=chat_id,
                                 sticker=sticker_list[sticker_index])

            elif lotto < 17:
                update.message.reply_text("Ole hyvä")

        elif "markku" in message and "istu" in message:
            if lotto < 91:
                bot.send_message(chat_id=chat_id, text="*istuu*")
            else:
                bot.send_message(chat_id=chat_id, text="*paskoo lattialle*")

        elif "huono markku" in message:
            bot.send_message(chat_id=chat_id, text="w00F")

        elif "markku perkele" in message:
            bot.send_message(chat_id=chat_id, text="woof?")

        elif "filmi" in message and lotto < 11:
            bot.send_message(chat_id=chat_id, text="Filmi best")
Ejemplo n.º 18
0
    def topten(self, bot, update, args):
        user_id, chat_id = get_ids(update)

        if self.on_timeout(user_id, chat_id):
            return

        # argumenttejä pitää olla vain yksi. ei errorviestiä koska tätä varmaan painetaan vahingossa usein
        if len(args) != 1:
            return

        # db:ltä käytössä olevat laskurit
        valid_counters = self.db.get_counters()

        # errorviesti jos argumentti ei vastaa laskuria
        if args[0] not in valid_counters:
            counters = ", ".join(valid_counters)
            reply = "Väärä laskurin nimi. Käytettävät laskurit: " + counters + "."
            bot.send_message(chat_id=chat_id, text=reply)

            return

        text = toptenlist(self.db, chat_id, args[0])

        bot.send_message(chat_id=chat_id, text=text)
Ejemplo n.º 19
0
    def korona(self, bot, update, args):
        _, chat_id = get_ids(update)

        msg = "Pese kädet, vältä turhaa ihmiskontaktia ja tule hengaamaan virtuaalipimiölle: https://discord.gg/kkPgMjV"
        bot.send_message(chat_id=chat_id, text=msg)
Ejemplo n.º 20
0
 def test_equals(self):
     update = DummyUpdate(chat=DummyChat('609'),
                          from_user=DummyUser('1377', 'kurkkumopo'))
     self.assertEqual(get_ids(update), ('1377', '609'))
Ejemplo n.º 21
0
 def test_get_ids(self):
     update = DummyUpdate(chat=DummyChat(123123),
                          from_user=DummyUser(456456, 'moippa'))
     self.assertEqual(get_ids(update), (456456, 123123))
Ejemplo n.º 22
0
    def start(self, bot, update, args):
        _, chat_id = get_ids(update) # Ignoraa user_id, tätä käytetään paljon

        bot.send_message(chat_id=chat_id, text="Woof woof")
Ejemplo n.º 23
0
    def camera_versus(self, bot, update, args):
        _, chat_id = get_ids(update)

        msg = camera_versus_text()
        bot.send_message(chat_id=chat_id, text=msg)