def main_loop(name="Calculon", channel="#servers", emoji=":calculon:"):

    while True:
        attachments = [
            SystemUsageAttachment(),
            ProcessReportAttachment()
        ]
        if restart_required():
            attachments.insert(0, Attachment("Restart Required", "danger", text="Calculon needs a break."))

        m = Message('Running status:', time.ctime(), emoji=emoji, attachments=attachments)
        m.send(POST_URL, username=name, channel=channel)
        time.sleep(60 * 60 * 6)
Exemplo n.º 2
0
    def create_global_message(self, targetMid, exception):
        message = Message()
        message.senderMid = 'global'
        message.targetMid = targetMid
        message.messageType = 'error'
        message.createTime = datetime.datetime.today().strftime(
            "%Y-%m-%d %H:%M:%S")
        message.senderTime = message.createTime
        message.tnsNumber = 0
        message.data = {"exception": exception}

        return message
Exemplo n.º 3
0
    def replyMessage(self, receivedMessage, state = False, msg = 'error info.', **kwargs):
        """
        """
        kwargs["state"] = state
        kwargs["message"] = msg

        return Message(messageType = self.messageType, targetMid = receivedMessage.senderMid, tnsNumber = receivedMessage.tnsNumber, data = kwargs)
Exemplo n.º 4
0
    def __parseMessageData(self, message):
        type = content = sender = senderNickname = channel = content = timestamp = None

        if (message["t"] == "MESSAGE_CREATE"):
            type = messageType.MESSAGE
            sender = message["d"]["author"]['id']
            senderNickname = message["d"]['author']['username']
            channel = message['d']['channel_id']
            content = message["d"]["content"]

            self.logger.info(
                "Message Recieved: [Name:{}][UID:{}][CID:{}]: {}".format(
                    senderNickname, sender, channel, content))
        else:
            return None

        if (sender == self.uid):
            return None

        return Message(type,
                       sender,
                       channel,
                       content,
                       senderNickname=senderNickname,
                       timestamp=time.time())
Exemplo n.º 5
0
    def _parse_message(self, message):
        type = content = sender = sender_name = channel = content = timestamp = None

        if message["t"] == "MESSAGE_CREATE":
            type = messageType.MESSAGE
            id = message["d"]['id']
            sender = message["d"]['author']['id']
            sender_name = message["d"]['author']['username']
            channel = message["d"]['channel_id']
            content = message["d"]['content']

            self.logger.info(
                "Message Recieved: [Name:{}][UID:{}][CID:{}]: {}".format(
                    sender_name, sender, channel, content))
        else:
            return None

        if sender == self.connectorCache['self']['id']:
            return None

        return Message(type,
                       id,
                       sender,
                       channel,
                       message,
                       content=content,
                       sender_name=sender_name,
                       timestamp=time.time())
Exemplo n.º 6
0
    def get_messages(self):
        """
        Возвращаем экземпляр класса Message при итерировании
        :return: Message
        """

        for message in self.client.iter_messages(self.base_url, limit=self.limit):
            yield Message(self.base_url, message.text, datetime_=message.date)
Exemplo n.º 7
0
def message_inject():
    target_topic = input("Enter the name of the topic you want to inject")
    target_node = input("Enter the name of the node you want to inject to")
    target_message = input("Enter the message you want to inject (json)")
    for node in node_list:
        if node.name == target_node:
            for topic in topic_list:
                if topic.name == target_topic:
                    exploit.message_injection(target_node=node, target_topic=topic, node_name=node_name,
                                              message=Message.from_json(target_message))
    print("Failed to find the topic to inject")
Exemplo n.º 8
0
def DamagedReport(name, location, damage):
    with app.app_context():
        msg = Message(
            subject="Damaged Report!",
            sender=app.config.get("MAIL_USERNAME"),
            recipients=["*****@*****.**"
                        ],  # replace with your email for testing
            body=
            "The following tablet {} from {} has been reported with a {} issue."
            .format(name, location, damage))
        mail.send(msg)
    return jsonify({'message': 'Your message has been sent successfully'}), 200
Exemplo n.º 9
0
    def _parse_discord_message(self, message):
        type = messageType.MESSAGE
        id = message['id']
        sender = message['author']['id']
        sender_name = message['author']['username']
        channel = message['channel_id']
        content = message['content']

        self.logger.debug(
            "Message Parsed: [Name:{}][UID:{}][CID:{}]: {}".format(
                sender_name, sender, channel, content))

        return Message(type,
                       id,
                       sender,
                       channel,
                       message,
                       content=content,
                       sender_name=sender_name,
                       timestamp=time.time())
Exemplo n.º 10
0
    def __parseMessageData(self, message):
        type = content = sender = channel = content = timestamp = None

        if not ("type" in message):
            return

        if (message["type"] == "message"):
            type = messageType.MESSAGE
            sender = message["user"]
            channel = message["channel"]
            content = message["text"]

        else:
            with open('unhandled_messages.txt', "a+") as file:
                file.write(json.dumps(message))

            return None

        if (sender == self.uid):
            return None

        return Message(type, sender, channel, content, timestamp=time.time())
Exemplo n.º 11
0
 def send_message(self, socket, message, payload=None, flags=0):
     message = Message(message, payload)
     message.master_id = self.node_id
     super(ZMQWorkManager,self).send_message(socket, message, payload, flags)
Exemplo n.º 12
0
#!/usr/bin/env python
#  -*- coding:utf-8 -*-
"""
    チャットボット LINE 操作 エントリポイント
"""
from definition.config import Config
from flask import Flask, request, abort, render_template
from core import Message

from linebot import (LineBotApi, WebhookHandler)
from linebot.models import (MessageEvent, TextMessage, TextSendMessage,
                            ImageSendMessage)
from linebot.exceptions import (InvalidSignatureError, LineBotApiError)

config = Config()
message = Message()

app = Flask(__name__, static_folder=config.static_folder)
line_bot_api = LineBotApi(config.token)
handler = WebhookHandler(config.secret)


@app.route("/")
def index():
    return render_template('index.html', title="hello excpyon")


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']
Exemplo n.º 13
0
 def parse_message(self, json):
     message_from = self.parse_player(json['from'])
     del json['from']
     return Message(**json, message_from=message_from)
Exemplo n.º 14
0
async def start_crawler(update: Update, context: CallbackContext) -> None:
    # Список каналов
    channel_list = get_settings()['telegram_chat_links_list']

    # Чат, в который мы будем отправлять сообщение
    # CHAT_ID = get_settings()['chat_to_send_events_id']
    chat_id = get_settings()['chat_id_to_send_polls']

    # Получаем необходимые настройки
    settings = get_settings()

    questions = [u'\U0001f44d', u'\U0001f44e']

    async with TelegramClient(settings['username'], settings['api_id'],
                              settings['api_hash']) as client:

        for chanel in channel_list[:1]:

            async for message in client.iter_messages(chanel, limit=10):

                message = Message(chanel, message.text, datetime_=message.date)
                # Инициализация детектора и передача текста детектору
                detector = AlgorithmicFilter(message)
                # Определение текста на начиличие заданных тем
                is_IS_event = detector.detect_event(
                    True) and detector.detect_is(True)

                if is_IS_event:

                    context.bot.send_message(
                        chat_id,
                        detector.message.description,
                        parse_mode=ParseMode.HTML,
                    )

                    message_to_send = context.bot.send_poll(
                        # update.effective_chat.id,
                        chat_id,
                        'Как тебе новость?',
                        questions,
                        is_anonymous=False,
                        allows_multiple_answers=False,
                    )

                    # Сохранение информации об опросе для последующего использования
                    payload = {
                        message_to_send.poll.id: {
                            "options": {question: 0
                                        for question in questions},
                            "questions":
                            questions,
                            "message_id":
                            message_to_send.message_id,
                            "chat_id":
                            update.effective_chat.id,
                            "all_answers":
                            0,
                            "text":
                            detector.message.description + '\n#ID: ' +
                            str(message_to_send.message_id)
                        }
                    }

                    context.bot_data.update(payload)