Example #1
0
    def register(self, chat_p=None):
        """Logs a new chat to the daemon and hosts it.
		- chat_p : None - A nameless chat is created and hosted.
		- chat_p : str - creates a chat named as {chat_p} and registers it.
		- chat_p : chat.Chat - registers the chat."""
        if isinstance(chat_p, str):
            chat_p = chat.Chat(name=chat_p)
            self.register(chat_p)
        elif chat_p is None:
            chat_p = chat.Chat()
            self.register(chat_p)
        elif isinstance(chat_p, chat.Chat):
            uri = str(self.daemon.register(chat_p))
            self.chats.append((chat_p.name, uri))
Example #2
0
def chat_nessage_hendler(message):
    #Если сообщение пришло в ЛК
    if message.chat.type == "private":
        pass

    #Если сообщение пришло в чат
    else:
        #Вызов класса Chat
        target_chat = chat.Chat(message.chat.id)
        #Выбираем обьект Чата из БД
        check_chat = target_chat.init_chat("obj")

        if check_chat[3] != "No":

            i = 0

            while i <= len(c.box):
                if c.box[i][0:-1] in message.text:
                    break
                i += 1

                if i == len(c.box):

                    c.bot.delete_message(message.chat.id, message.message_id)

                    if check_chat[2] != "No":
                        
                        #Это сообщение обьясняет причину удаления сообщения юзера
                        c.bot.send_message(message.chat.id, "заткнись сука")
                        break
                    else:
                        break
Example #3
0
 def Join(self, chat, prefix):
     if chat not in self.connections.keys():
         self.connections[chat] = chat.Chat(chat, prefix, self)
         self.chats.append(chat)
         return True
     else:
         return False
Example #4
0
    def test01_not_reserved(self):
        event = {}
        event["body"] = None

        chat_id = 10

        event["pathParameters"] = {}
        event["pathParameters"]["chatId"] = chat_id

        with mock.patch(
                "UnreserveChatById.lambda_function.Session") as mock_session:
            mock_query = mock_session.return_value.query
            mock_get = mock_query.return_value.get

            mock_chat = chat.Chat()
            mock_chat.chat_status = chat.ChatStatus.ACTIVE
            mock_chat.aspiring_professionals = ["Henry"]

            mock_get.return_value = mock_chat

            actual = unreserve.handler(event, context)

        expected = {"statusCode": 400, "body": json.dumps({})}

        self.assertEqual(actual["statusCode"], expected["statusCode"], \
                         self.msg_status_code.format(expected["statusCode"], \
                                                     actual["statusCode"]))
Example #5
0
 def do_stuff(self, username, message, net_socket):
     command_to_remove = message.replace("!remove", "")
     command_to_remove = command_to_remove.strip()
     print("Remove: {}".format(command_to_remove))
     if(not "!" in command_to_remove):
         command_to_remove = "!{}".format(command_to_remove)
     print("command keys: {}".format(self.commands.keys()))
     if(not command_to_remove in self.commands.keys()):
         chat_obj = chat.Chat("Command {} not found in command list".format(command_to_remove))
         chatcommands.chat(net_socket, chat_obj.get_chat_text())
         return
     self.commands.pop(command_to_remove)
     with open(os.path.dirname(os.path.realpath(__file__))+'/commands.json', 'w') as commands_file:
         commands_file.write(json.dumps(self.commands))
     chat_obj = chat.Chat("Removed command {}".format(command_to_remove))
     chatcommands.chat(net_socket, chat_obj.get_chat_text())
 def do_stuff(self, username, message, net_socket, tags):
     is_resub = tags[tagsutil.MSG_ID_KEY] == "resub"
     chat_obj = chat.Chat()
     chat_obj.add_decorator(
         chatdecorators.SubOrResubDecorator(
             username, tags[tagsutil.SUB_MONTH_KEY],
             tags[tagsutil.SUB_PLAN_KEY].replace("\s", " "), is_resub))
     chatcommands.chat(net_socket, chat_obj.get_chat_text())
Example #7
0
	def newChat(self, uri_str):
		uri = ch.ParseSipUri(uri_str)
		if not uri: return None
			
		chat = ch.Chat(self.app, self, uri)
		self.chatList.append(chat)
		self.app.updateWindowMenu()
		return chat
Example #8
0
 def click(self, obj = None):
     self.i += 1
     pytanie = self.inp.text
     self.adapter.data.append('Ty: '+pytanie)
     odpowiedz = chat.Chat().odpowiedz(pytanie)
     self.adapter.data.append('Franek: ' + odpowiedz)
     if self.i >= 6:
         self.list_view.scroll_to((self.i*2)-9)
     self.inp.text = ""
Example #9
0
def delete_chat(message):
    if message.left_chat_member.id == c.bot.get_me().id:
        target_chat = chat.Chat(message.chat.id)
        check_chat = target_chat.init_chat("chat")

        if check_chat is True:
            target_chat.delete_chat(message.chat.id)
            #тут сообщение выдает ошибку
            print("Прошло удаление бота в чате ", message.chat.title)
Example #10
0
 def __process_xfr(self, command):
     sb = split(command.args[1], ':')
     server = (sb[0], int(sb[1]))
     cr = self.chat_requests[command.trn]
     invitee = cr.invitee
     chat_ = chat.Chat(self, server, command.args[3], self.passport_id,
                       self.display_name, None, invitee)
     self.active_chats[chat_.session_id] = chat_
     self.callbacks.chat_started(chat_)
Example #11
0
 def __host(self):
     dialog = ConnectDialog(self)
     if not dialog.was_canceled():
         try:
             if self.__net is not None and not self.__net.is_done():
                 raise RuntimeError('Chat is already running.')
             self.__net = chat.Chat(dialog.get_username(),
                                    self.__got_message, self.__thread_error)
             self.__net.host(dialog.get_address(), dialog.get_port())
         except RuntimeError as e:
             tkinter.messagebox.showerror('Error!', str(e))
Example #12
0
def reg_cchat(message):
    if message.new_chat_member.id == c.bot.get_me().id:
        target_chat = chat.Chat(message.chat.id)
        check_chat = target_chat.init_chat("chat")

        if check_chat is False:
            target_chat.create_chat(message)
            c.bot.send_message(message.chat.id, "Вы зарегали чат, скоро Эрек напишет правила")
            print("Прошла регистрация в чате ", message.chat.title)
        else:
            c.bot.send_message(message.chat.id, "Бот уже зарегистрировал ваш чат")
Example #13
0
def addNewChat():
    print("type chat id: ")
    new_chat_id = int(input())
    new_chat = chat.Chat(new_chat_id, session)
    chats.append(new_chat)
    new_cthread = mthread.refreshingThread(new_chat, 0.5)
    threads.update({new_chat_id: new_cthread})
    new_cthread.setName(new_chat.chat_name)
    new_cthread.daemon = True
    new_cthread.start()
    print("Added new Chat: " + new_chat.chat_name)
Example #14
0
    def __init__(self, clientsocket, data):
        self.data = data
        try:
            self.chatlisten = chat.Chat("listen")
            threading.Thread(self.chatlisten.main())
        except:
            print("Error Launching Chat")

        self.gamep2p = gamep2p.Gamep2p('listen')
        threading.Thread(self.gamep2p.main())
        threading.Thread(self.client())
        self.sock = clientsocket
Example #15
0
 def get_game_info(self, sock, msg, username):
     game = None
     try:
         game = Game()
         print(game.__str__())
     except exceptions.NotStreamingException as e:
         chat_obj = chat.Chat("@{} isn't streaming right now!".format(config.USERNAME))
         chat_obj.add_decorator(chatdecorators.UsernamePrefixDecorator(username))
         chatcommands.chat(sock, chat_obj.get_chat_text())
         return
     except exceptions.GameNotFoundException as e:
         chat_obj = chat.Chat("We couldn't find \"{}\" in the IGDB database. Want to help out? Add it to the database! https://www.igdb.com/".format(e.message))
         chat_obj.add_decorator(chatdecorators.UsernamePrefixDecorator(username))
         chatcommands.chat(sock, chat_obj.get_chat_text())
         return
     except Exception as e:
         chat_obj = chat.Chat("Weird, something else went wrong.")
         chat_obj.add_decorator(chatdecorators.UsernamePrefixDecorator(username))
         chatcommands.chat(sock, chat_obj.get_chat_text())
         return
     print(game.__str__())
     if game:
         chat_obj = chat.Chat()
         msg = msg.replace("\r", "")
         msg = msg.replace("\n", "")
         args = re.split(WHITESPACE_RE, msg)
         args.pop(0)
         if not args:
             chat_obj.add_decorator(chatdecorators.SummaryDecorator(game))
         elif "summary" in args:
             chat_obj.add_decorator(chatdecorators.SummaryDecorator(game))
         elif "beat-time" in args:
             chat_obj.add_decorator(chatdecorators.TimeToBeatDecorator(game))
     print(game.__str__())
     chat_obj.add_decorator(chatdecorators.URLDecorator(game))
     chat_obj.add_decorator(chatdecorators.UsernamePrefixDecorator(username))
     chatcommands.chat(sock, chat_obj.get_chat_text())
Example #16
0
 def __process_rng(self, buf):
     cmdline = split(buf)
     session_id = cmdline[1]
     sb = split(cmdline[2], ':')
     server = (sb[0], int(sb[1]))
     hash = cmdline[4]
     passport_id = cmdline[5]
     display_name = url_codec.decode(cmdline[6])
     try:
         chat_ = chat.Chat(self, server, hash, passport_id, display_name,
                           session_id)
     except Error, e:
         if e.code == 1:  # connection closed
             return
         raise e
Example #17
0
def parse(filename):
    events = []
    authors = {}
    with codecs.open(filename, encoding='utf-8') as f:

        last_event_type = None

        for line in f.readlines():

            event_type, fields = parse_event(line)

            if event_type is not None:

                dt = datetime.datetime.strptime(fields[0], '%d/%m/%y %H:%M:%S')

                # Create the author if it doesn't exist.
                if fields[1] not in authors:
                    authors[fields[1]] = Author(fields[1])
                author = authors[fields[1]]

                try:
                    params = dt, author, fields[2]
                except IndexError:
                    params = dt, author

                # This is horrible.
                if last_event_type == Message:
                    events[-1].text = events[-1].text.strip()

                newevent = event_type(*params)
                events.append(newevent)

            elif last_event_type == Message:
                events[-1].text += line
                event_type = Message

            last_event_type = event_type

    # This is horrible, again.
    if last_event_type == Message:
        events[-1].text = events[-1].text.strip()

    events = sorted(events, key=attrgetter('datetime'))
    return chat.Chat(events, authors.values())
Example #18
0
 def do_stuff(self, username, message, net_socket):
     command_to_add = message.replace("!add", "")
     split_pair = command_to_add.split("=")
     chat_obj = chat.Chat()
     if len(split_pair) != 2:
         exception = exceptions.FormatException("command = response")
         user_decorator = chatdecorators.UsernamePrefixDecorator(username)
         exception_decorator = chatdecorators.ExceptionDecorator(exception)
         chat_obj.add_decorator(user_decorator)
         chat_obj.add_decorator(exception_decorator)
         chatcommands.chat(net_socket, chat_obj.get_chat_text)
         return
     split_pair[0] = split_pair[0].strip()
     split_pair[1] = split_pair[1].strip()
     text = self.commands["!{}".format(split_pair[0])] = split_pair[1]
     with open(os.path.dirname(os.path.realpath(__file__))+'/commands.json', 'w') as commands_file:
         commands_file.write(json.dumps(self.commands))
     chat_obj.add_decorator(chatdecorators.DictDecorator("Added command !{}".format(split_pair[0])))
     chatcommands.chat(net_socket, chat_obj.get_chat_text())
Example #19
0
    def handleConn(self, conn):

        data = conn.recv(4096)
        if data:
            hello = ipcMessage_pb2.Hello()
            hello.ParseFromString(data)

            if not hello.response:
                respHello = ipcMessage_pb2.Hello()
                respHello.response = True

                conn.send(respHello.SerializeToString())

        while True:

            #Receiving from client
            data = conn.recv(4096)
            if not data:
                break

            msg = ipcMessage_pb2.Message()
            msg.ParseFromString(data)

            if msg.chatId not in self.chatDict:
                self.chatDict[msg.chatId] = chat.Chat(self.g)

            self.chatDict[msg.chatId].addMessage(msg)

            respMsg = ipcMessage_pb2.Message()
            if msg.respond:
                respMsg.text = self.chatDict[msg.chatId].runNN()
                respMsg.chatId = msg.chatId
                respMsg.userId = msg.userId
                respMsg.time = msg.time
                respMsg.respond = True

                conn.send(respMsg.SerializeToString())

        conn.close()
Example #20
0
    def decode_object(o):
        if '__User__' in o:
            u = user.User(None, None)

            u.__dict__.update(o['__User__'])

            return u

        elif '__Message__' in o:
            m = user.Message(None, None)

            m.__dict__.update(p['__Message__'])

            return m

        elif '__Chat__' in o:
            c = chat.Chat()

            c.__dict__.update(o['__Chat__'])

            return c

        return o
Example #21
0
def start(message):
    if message.chat.type == "private":
        pass
    else:
        #Вызов класса Чат
        target_chat = chat.Chat(message.chat.id)
        #Проверка чата на существование
        check_chat = target_chat.init_chat("bool")

        #Если чат существует в БД то:
        if check_chat is True:
            this_chat = target_chat.init_chat("obj")

            admins = c.bot.get_chat_administrators(message.chat.id)
            for i in admins:
                if i.user.id == message.from_user.id:
                    if this_chat[2] == "No":
                        target_chat.update_chat(this_chat[0], this_chat[1], "Yes", this_chat[3])
                        c.bot.send_message(message.chat.id, "Системные сообщения включены")
                    elif this_chat[2] == "Yes":
                        c.bot.send_message(message.chat.id, "В этом чате уже включены системные сообщения")

        else:
            c.bot.send_message(message.chat.id, "Ваш чат не зарегестрирован")
Example #22
0
 def updprof_addfr_remfr_chat_gui(self):
     """ Update Profile and Move to Chat Windows choosing GUI """
     img = "choose.gif"
     msg = "What to do?"
     choices = ("Chat!", "Update Profile!", "Add Friends!",
                "Remove Friends!", "See Others Profile!", "Exit")
     reply = eg.buttonbox(msg, title=self.title, image=img, choices=choices)
     if reply == "Chat!":
         ch = chat.Chat(self.username, self.re)
         if ch.chat_window_gui() == 0:
             self.updprof_addfr_remfr_chat_gui()
     elif reply == "Update Profile!":
         rl = self.update_profile()
         self.updprof_addfr_remfr_chat_gui()
     elif reply == "Add Friends!":
         if self.add_friends() == 1:
             msg = "Friends Added Successfully!"
             eg.msgbox(msg, self.title)
         self.updprof_addfr_remfr_chat_gui()
     elif reply == "Remove Friends!":
         if self.remove_friends() == 1:
             msg = "Selected Friends Removed Successfully!"
             eg.msgbox(msg, self.title)
         self.updprof_addfr_remfr_chat_gui()
     elif reply == "See Others Profile!":
         msg = "Choose the Person to see details"
         choices = self.re.keys('*')
         ch = eg.choicebox(msg, self.title, choices)
         if ch is not None:
             data = json.loads(self.re.get(ch))
             msg = """ Username:\t%s \n\n Name:\t\t%s \n\n EmailID:\t\t%s """ \
                   % (ch, data[2], data[3])
             eg.msgbox(msg, self.title)
         self.updprof_addfr_remfr_chat_gui()
     else:
         exit(0)
Example #23
0
    def test02_valid_id_invalid_status(self):
        event = {}
        event["body"] = None

        chat_id = 10

        event["pathParameters"] = {}
        event["pathParameters"]["chatId"] = chat_id

        with mock.patch(
                "ReserveChatById.lambda_function.Session") as mock_session:
            mock_query = mock_session.return_value.query
            mock_get = mock_query.return_value.get
            mock_chat = chat.Chat()
            mock_chat.chat_status = chat.ChatStatus.DONE
            mock_get.return_value = mock_chat

            actual = reserve.handler(event, context)

        expected = {"statusCode": 409, "body": json.dumps({})}

        self.assertEqual(actual["statusCode"], expected["statusCode"], \
                         self.msg_status_code.format(expected["statusCode"], \
                                                     actual["statusCode"]))
Example #24
0
import os
from twitchio.ext import commands
import asyncio
import kekfunc
import emote
import chat
from datetime import datetime
import csv
import pasta
import numpy as np

# GENERAL SETUP
# load channel config and initialize chat object
chat_config = chat.Chat.load_chat_config('utils/config.yaml')
chat_object = chat.Chat(chat_config)
# load pasta list
pasta_list, pasta_id = pasta.load_pasta('Data/copypasta/deep_fake_pasta.csv')
# COLORS FOR TERMINAL
print_color_green = '\033[92m'
print_color_cyan = '\u001b[36;1m'
print_color_red = '\u001b[31m'
print_color_reset = '\u001b[0m'


# set up the bot
class Bot(commands.Bot):
    def __init__(self):
        super().__init__(irc_token=os.environ['TMI_TOKEN'],
                         client_id=os.environ['CLIENT_ID'],
                         client_secret=os.environ['CLIENT_SECRET'],
                         nick=os.environ['BOT_NICK'],
Example #25
0
    currentEndurance.insert(INSERT, c.currentE)
    currentIntelligence.insert(INSERT, c.currentI)
    currentPerception.insert(INSERT, c.currentP)
    currentSocial.insert(INSERT, c.currentS)
    currentAgilite.insert(INSERT, c.currentA)
    currentChance.insert(INSERT, c.currentC)


##########################################################"""HEBERGER"""

MUTEX = RLock()
queue1 = queue.Queue()
queue2 = queue.Queue()

SERVER = server.Server(queue1, queue2)
CHAT = chat.Chat(queue2, queue1, MUTEX)


class Client():
    def __init__(self, q, p, mutex):
        #Thread.__init__(self)
        self.isClient = False
        self.queue_v_c = q
        self.queue_f_c = p
        self.mutex = mutex

    def connect(self, ip, port, name):
        try:
            self.ip = ip
            self.port = port
            self.name = name
Example #26
0
def timed_chat():
    intro_chat = chat.Chat()
    intro_chat.add_decorator(chatdecorators.MotdDecorator())
    chatcommands.chat(s, intro_chat.get_chat_text())
    msg_count = 0
    last_msg_time = time.time()
Example #27
0
from logging.handlers import RotatingFileHandler
from flask import Flask, request, session, g, redirect, url_for, \
    abort, render_template, flash, make_response, jsonify, json, \
    send_from_directory
from flask.views import MethodView
from uadetector.flask import UADetector
from decimal import Decimal
from urllib.error import HTTPError
from urllib.parse import quote, unquote
import chat

application = Flask(__name__)
UADetector(application)

chat.FLAGS.out_dir = 'nmt_model/'
chatbot = chat.Chat()
default_hparams = chat.create_hparams(chat.FLAGS)
chatbot.nmt_main(chat.FLAGS, default_hparams)


@application.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(application.root_path, 'static'),
                               '/images/favicon.ico',
                               mimetype='image/vnd.microsoft.icon')


@application.route('/')
def root():
    return render_template('home.html')
Example #28
0
def send():
    while True:
        time.sleep(1)
        network.s.send(chat.type_message.encode())


def recv():
    while True:
        time.sleep(0.5)
        data = network.s.recv(1024)
        chat.chat_text.config(state="normal")
        chat.chat_text.insert(tk.INSERT, data)
        chat.chat_text.config(state="disabled")


nicks = ["seifer", "dima"]
network = network.Network()
log = log.Log(network.s, network.connected)

log.window()
nick = network.s.recv(1024)
chat = chat.Chat(network.s, nick.decode())
chat.add_contacts(nicks)
send_thread = threading.Thread(target=send)
send_thread.daemon = True
send_thread.start()
receive_thread = threading.Thread(target=recv)
receive_thread.daemon = True
receive_thread.start()
chat.window()
Example #29
0
 def Start(self, prefix, chats=None):
     for x in chats:
         if x not in self.connections.keys():
             self.connections[x] = chat.Chat(x, prefix, self)
             self.chats.append(x)
     self.myHomies()
Example #30
0
    def signup(self):
        """ New user Signup class """
        msg = " Enter Details!"
        fnames = [
            "Full Name(atleast 6 chars): ", "Email-ID: ", "UserName:"******"Security Code(Atleast 6 chars):",
            "Password(Atleast 8 chars that includes alpha-numeric):"
        ]
        errormsg = ""
        fvals = []
        mac = get_mac()
        #print mac
        fvals = eg.multpasswordbox(msg, self.title, fnames)
        if fvals is not None:
            if fvals[0] == '' or fvals[1] == '' or fvals[2] == '' or \
            fvals[3] == '' or fvals[4] == '':
                errormsg = "Fill all Boxes!"
            else:
                # Checking if username exists or not

                if len(fvals[0]) >= 6:
                    if self.check_emailid(fvals[1]):
                        if len(fvals[2]) >= 3:
                            if self.re.exists(fvals[2]) == False:
                                if len(fvals[3]) >= 6:
                                    if len(fvals[4]
                                           ) >= 8 and self.check_password(
                                               fvals[4]):
                                        pas = self.make_password(fvals[4])
                                        # Empty list => friends of user
                                        # Value in DB: [Password,SC,Name,EmailID,Friend list,mac]
                                        val = json.dumps([
                                            pas, fvals[3], fvals[0], fvals[1],
                                            [], mac
                                        ])
                                        self.re.set(fvals[2], val)
                                        self.re.bgsave()
                                        # Making Queues for every signup client so that his friends can send him
                                        # msgs when he is Offline also, and user can get them later :)
                                        ch = chat.Chat(fvals[2], self.re)
                                        ch.connection()
                                        eg.msgbox("You Signup Successfully!",
                                                  self.title)
                                        return 1
                                    else:
                                        errormsg = """ Password should contain atleast 1 digit,
1 uppercase chars, 1 lowercase chars & should be of atleast 8 chars! """
                                else:
                                    errormsg = "Security Code should be of atleast 6 in length"
                            else:
                                errormsg = "UserName Already Exists"
                        else:
                            errormsg = "UserName should be of atleast 4 chars"
                    else:
                        errormsg = "Enter EmailID in proper format"
                else:
                    errormsg = "Name should be of atleast 6 chars"
            if errormsg != "":
                eg.msgbox(errormsg, title=self.title)
                return 2
        else:
            return 0