def kick_user(self, uid, tid, time_removed, time_to_rejoin=0): if uid not in self.users: self.track_new_user(uid) user = self.users[uid] if time_to_rejoin != 0: chat = Chat(tid, time_removed, rejoin_time=time_to_rejoin) user.add_chat(chat, timed=True) else: chat = Chat(tid, time_removed) user.add_chat(chat) self.removeUserFromGroup(uid, thread_id=tid) self.save_to_file()
def __init__(self, host=None, port=None, commander_name=None, bot_name=None): self.server_host = host self.server_port = port self.config = config self.eventregister = EventRegister(self) self.eventregister.setup() self.commander = Commander(commander_name) self.chat = Chat(self) self.stats = Statistics() self.bot = BotEntity(self, bot_name) self.game_ticks = 0 self.connected = False self.logged_in = False self.protocol = None self.factory = None self.entities = None self.inventories = inventory.InvetoryContainer(self) self.grid = None self.sign_waypoints = None self.dimension = None self.dimensions = [Dimension(self), Dimension(self), Dimension(self)] self.spawn_position = None self.game_mode = None self.difficulty = None self.players = defaultdict(int) self.last_tick_time = datetime.now() self.period_time_estimation = config.TIME_STEP utils.do_later(config.TIME_STEP, self.tick)
def handler(event, context): authorized_user_types = [ UserType.ADMIN, ] success, _ = check_auth(event['headers']['Authorization'], authorized_user_types) if not success: return http_status.unauthorized() body = json.loads(event["body"]) user_email = body.get('email') if not user_email: return http_status.bad_request() chat_freq = 4 attributes = { "custom:user_type": "MENTOR", "custom:declared_chats_freq": str(chat_freq), "custom:remaining_chats_freq": str(chat_freq) } admin_update_user_attributes(user_email, attributes) admin_enable_user(user_email) session = Session() for i in range(chat_freq): chat_type = ChatType["ONE_ON_ONE"] chat = Chat(chat_type=chat_type, chat_status=ChatStatus.PENDING, senior_executive=user_email) session.add(chat) session.commit() session.close() return http_status.success()
def enter(self): self.login = self.LoginLineEdit.text() self.password = self.PasswordLineEdit.text() self.con = sqlite3.connect("dollars.db") cur = self.con.cursor() result = cur.execute( """SELECT login, password FROM users WHERE login == ? AND password == ?""", (self.login, self.password)).fetchall() if len(result) > 0: result = result[0] if result[0] == self.login and str(result[1]) == self.password: self.name = self.login self.chat = Chat(self.name) self.chat.show() self.close() else: self.error.setText("login or password isn't correct") self.LoginLineEdit.setText('') self.PasswordLineEdit.setText('') else: self.error.setText("login or password isn't correct") self.LoginLineEdit.setText('') self.PasswordLineEdit.setText('')
def loop(): twitch = Chat() twitch.connect() time.sleep(3) while True: try: response = twitch.get_message() #DEBUG #print("Reponse:"+response) if response == "PING :tmi.twitch.tv\r\n": twitch.pong() elif response: evaluate_message(response) except socket.timeout: debug_event = True #print("Socket Timed Out!") except socket.error: print("Socket Error, Connection closed!") time.sleep(1) twitch.connect() except Exception as e: print("Unknown error") print(e) #TODO: Find a better sleep cycle. Rate limiting already in place time.sleep(1 / cfg.RATE)
def __init__(self, parent, width, height): super(GameFrame, self).__init__(parent) self.width = width self.height = height self.resize(self.width, self.height) #Chat self.chatMode = False self.chat = Chat(10,self.height - 210, 600, 200) #Entities self.entities = [] #self.entities.append(Entity()) #e = Entity() #e.setPos(200,200) #self.entities.append(e) self.character = Character() self.character.setPos(300,300) self.otherPlayers = [] #Server connection self.offline = False self.sock = socket.socket() self.sock.connect(('127.0.0.1', 1338)) self.updatesPerServerSync = 5 self.serverSyncCounter = 0
def hapusChat(): with Chat() as c_chat: data = request.get_json() id_chat = data["id_chat"] res = c_chat.hapusChat(id_chat) return jsn(1, "OK") if res else jsn(0, "ERR")
def incoming_call(self, prm): call = Call(self.acc, call_id=prm.callId) call_prm = pj.CallOpParam() # Ringing State call_prm.statusCode = pj.PJSIP_SC_RINGING call.answer(call_prm) # Set uri call.uri = call.getInfo().remoteUri iid = call.uri.split(':')[1].split('@')[0] if msg.askquestion('Incoming Call', 'Accept call from ' + iid + ' ?', default=msg.YES): # If not exist current buddy, then create if iid not in self.buddy_list: # Initialize buddy bud = Buddy(self, iid) # Initialize configuration of buddy bud_cfg = pj.BuddyConfig() bud_cfg.uri = 'sip:' + iid + '@' + self.domain # Create buddy bud.cfg = bud_cfg bud.create(self.acc, bud.cfg) bud.subscribePresence(True) # Push into buddy_list self.buddy_list[iid] = bud self.update_buddy(bud) # If not exist current chat dialog, then create if iid not in self.chat_list: self.chat_list[iid] = Chat(self.acc, self.buddy_list[iid], self) # Inform the corresponding chat self.chat_list[iid].receive_call(call) else: call.hangup(call_prm)
def __init__(self, slack_client, channel, players): self.last_message = None self.slack_client = slack_client self.channel = channel self.players = players self.chat = Chat(slack_client, channel) print str(channel)
def do(): f = open(CHATS_COLLECTION_NAME) tags = json.loads(f.read()) f.close() chats_by_id = {} for id, tags_json in tags.items(): tags = [] for j in tags_json: user_json = j["from"] first_name = user_json.get("first_name", "") last_name = user_json.get("last_name", "") username = user_json.get("username", "") user = User(user_json["id"], first_name, last_name, username) tag = Tag(j["text"], user, j["date"]) tags.append(tag) admin = 58699815 chats_by_id[id] = Chat(id, tags=tags, admin=admin) encoded = jsonpickle.encode(chats_by_id) f = open(CHATS_COLLECTION_NAME, "w") f.write(encoded) f.close()
def __init__(self): json = None self.summary = None self.url = None self.beat_time = None self.game_chat = None try: self.api = APIS() json = self.api.get_game_info() print(json) self.name = json['name'] if 'summary' in json: self.summary = json['summary'].replace('\n', ' ') if len(self.summary) > 400: self.summary = self.summary[:400] + '... ' else: self.summary = None self.url = json['url'] self.beat_time = self._get_times_to_beat(json) self.game_chat = Chat('@{} is playing {}. '.format( config.USERNAME, self.name)) except exceptions.NotStreamingException: raise exceptions.NotStreamingException() except exceptions.GameNotFoundException: raise exceptions.GameNotFoundException( message=APIS().get_game_streaming())
def get_chat(self, chat_id: int) -> Chat: """Get a Chat from BotData""" # Create a Chat object for chat_id if not found if not self.chats.get(chat_id): self.chats.update({chat_id: Chat(chat_id)}) return self.chats.get(chat_id)
def start_chat(self): self.__client_name = self.__name.get().strip('\n').strip(' ') client_pass = self.__password.get().strip('\n').strip(' ') self.__my_cursor.execute( "SELECT * FROM users WHERE name=%s AND Password=%s", (self.__client_name, client_pass)) msg = self.__my_cursor.fetchone() if client_pass is not None and self.__client_name is not None: if not msg: Notification('the user doesn\'t exist').start() return self.__my_cursor.execute( "SELECT connected FROM users WHERE name=%s AND Password=%s", (self.__client_name, client_pass)) msg = self.__my_cursor.fetchone() if msg[0] == 'True': Notification('the user already connected to the chat').start() return else: sqlf = "UPDATE users SET connected='True' WHERE name=%s AND Password=%s" self.__my_cursor.execute(sqlf, (self.__client_name, client_pass)) self.__my_database.commit() name_len = len(self.__client_name) self.__client_name = str(name_len) + self.__client_name try: Chat(Host, Port, self.__client_name, self.__window, self.__start) except: Notification('The server is currently unavailable').start() sql = "UPDATE users SET connected='False' WHERE name=%s " self.__my_cursor.execute(sql, (self.__client_name[1:], )) self.__my_database.commit()
def test_chat_match_alternative(self): search_str = 'Zebra' res = { 'count': 1, 'similarity': 1, 'value': { 'subject': ('eels', 'Zebra Moray'), 'keywords': (('eel', 'snake-like'), ('zebra', 'strip', 'moray')), 'phrase': ('Zebra Moray', ), 'info': ({ 'name': 'Diet', 'value': 'Sea urchins, mollusks, and crustaceans.' }, ), 'isLeaf': True }, 'lastCount': 1, 'lastSimilarity': 1, 'matching': ('zebra', ), 'certainty': 2 } thisChat = Chat(flatten(resources), ['fishes', 'nothingthere']) self.assertEqual(thisChat.match(search_str), res)
def test_add_player(self): slack_client = MockSlackClient() manager = TeamManager(Chat(slack_client, 'foo')) manager.add_player(Player("p1", slack_client)) self.assertEqual(1, len(manager.players)) self.assertEqual("You have joined the game!", slack_client.api_calls[-1][1])
def __init__(self, parent, width, height): super(GameFrame, self).__init__(parent) self.width = width self.height = height self.resize(self.width, self.height) #Input self.keys = {} #Chat self.chatMode = False self.chat = Chat(10, self.height - 210, 600, 200) #World (holds map size, entities, characters/players) self.world = World() #Character character = Character() character.setName("Macke") character.setPos(300, 300) self.world.setCharacter(character) #Server connection self.threadHandler = ClientThread(self.world.getCharacter(), self.world.getOtherPlayers()) self.threadHandler.start()
def hello_world(): if request.method == 'PUT': print(request.json) errorStatement = request.json["errorstat"] bot = Chat() ans = bot.chatbot_response(errorStatement) return jsonify(ans)
def chatStarted(self): clickedItem = self.list.currentItem() if clickedItem is not None: user = str(self.list.currentItem().text()) ip = self.userList[user] if ip is not None: chat = Chat(self.username, user, ip, self.ciphers) self.chats[user] = chat
def tambahChat(): with Chat() as c_chat: rj = request.get_json() res = c_chat.tambahChat(rj['id_pengirim'], rj['id_penerima'], rj['pesan']) # return status return jsn(1, "OK") if res else jsn(0, "ERR")
def hapusChat(): with Chat() as c_chat: data = request.get_json() id_chat = data["id_chat"] res = c_chat.hapusChat(self,id_chat) if res: return jsn(1,"") else: return jsn(0,"")
def add_tag(self, chat_id, tag): chat = self.mapper.get_chat_by_id(chat_id) if not chat: chat = Chat(chat_id) elif len(chat.tags) >= 5: chat.tags.pop(0) chat.tags.append(tag) self.mapper.save_chat(chat)
def __init__(self, client): self.client = client self.state = 'main' # state main self.title_main = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'SocketGame', font=Font.f100) self.button_login = Button(DIM_MAIN_B, C.LIGHT_BLUE, POS_BLOG,'Log in') self.button_signup = Button(DIM_MAIN_B, C.LIGHT_BLUE, POS_BSIGN,'Sign up') self.button_credits = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE, LMARGE),'Credits',font=Font.f30) # state login self.title_login = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Log in', font=Font.f100) self.text_logusername = TextBox(DIM_TEXTBL,C.WHITE, (X_POS_TEXTBL, Y_POS_TEXTBL), 'Username:'******'Password:'******'Done', font=Font.f30) self.button_back = Button(DIM_NB, C.LIGHT_BLUE, POS_BBACK,'Back', font=Font.f30) # state signup self.title_signup = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Sign up', font=Font.f100) # state fail log self.text_faillog = TextBox(DIM_FAILT, C.WHITE, (X_POS_TEXTBL2, Y_POS_FAILT), 'Invalid username or password', font=Font.f25, TEXT_COLOR=C.RED) # state fail sign self.text_failsign = TextBox(DIM_FAILT, C.WHITE, (X_POS_TEXTBL2, Y_POS_FAILT), 'Username already taken', font=Font.f25, TEXT_COLOR=C.RED) # state logged self.title_logged = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Welcome', font=Font.f100) self.text_username = TextBox(DIM_LOGINP, C.WHITE, (LMARGE, LMARGE),'',marge=True) self.button_play = Button(DIM_MAIN_B, C.LIGHT_BLUE, POS_BPLAY, 'Play') self.chat_logged = Chat(DIM_CHAT, (MARGE,dim.y-DIM_CHAT[1]-MARGE), self.client) self.friends = Friends(DIM_FR, (dim.x-DIM_FR[0]-MARGE, E(250)), self.client) self.button_disconn = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE + E(250), MARGE+DIM_LOGINP[1]) ,'Disconnect',font=Font.f30) self.button_account = Button(DIM_LI_MAIN_B, C.LIGHT_BLUE, (LMARGE, MARGE+DIM_LOGINP[1]),'Account',font=Font.f30) # state env self.title_env = TextBox(DIM_TITLE, C.WHITE, POS_TITLE,'Env', font=Font.f100) self.text_wating = TextBox(DIM_TWAIT,C.WHITE, POS_TWAIT, 'Waiting for the other players...', font=Font.f30) self.button_exit = Button(DIM_BEXIT, C.LIGHT_BLUE, POS_BEXIT, 'Exit', font=Font.f30) self.teams = Teams self.teams.init(POS_TEAMS,DIM_TEAMS, client) # state account self.title_account = TextBox(DIM_TITLE, C.WHITE, (POS_TITLE[0], POS_TITLE[1] + E(100)),'', font=Font.f100) Stats.init(client, POS_STATSY) self.Stats = Stats
def send(event=None): # event is passed by binders. """Handles sending of messages.""" msg = my_msg.get() chat = Chat(msg, 'my name') my_msg.set("") # Clears input field. client_socket.send(pickle.dumps(chat)) if msg == "{quit}": client_socket.close() top.quit()
def from_json(self, json): chat = Chat(json['id']) for jFeed in json['feeds']: feed: Feed = Feed(jFeed['key'], jFeed['url']) feed.lastUpdate = jFeed['lastUpdate'] feed.addFilterBy(jFeed['filterBy']) chat.addfeed(feed) return chat
def __get_chat(self, _id): # получаем беседу chat = self.__chats.get(_id) # пробуем получить беседу if chat is None: # если не удачно _chat = self.vk.method('messages.getChat', {'chat_id': _id}) # запрашиваем беседу chat = Chat(_chat.get('id'), _chat.get('type'), _chat.get('title'), _chat.get('admin_id'), _chat.get('users')) self.__chats[_id] = chat # добавляем в кеш return chat
def setUp(self): random = RandomMock() self.slack_client = MockSlackClient() self.game_state = GameState(self.slack_client, random_func=random, chat=Chat(self.slack_client, "chat_chanel"), channel="chat_chanel") self.handler = InvalidHandler(self.game_state) self._add_players(self.slack_client, self.game_state)
async def start_chat(): server = random.choice(servers) proxy = await proxies.get() if manager.enable_proxies else None while 1: chat = Chat(manager, server, replies, proxy) await chat.start() if manager.enable_proxies: proxies.set_used(proxy) if not chat.connected: proxy = await proxies.get()
def __init__(self, word, player_drawing, game): self.word = word self.player_drawing = player_drawing self.player_guessed = [] self.skips = 0 self.time = 75 self.game = game self.player_scores = {player: 0 for player in self.game.players} self.chat = Chat(self) start_new_thread(self.time_thread, ())
def setUp(self): unittest.TestCase.setUp(self) random = RandomMock() self.slack_client = MockSlackClient() self.game_state = GameState(self.slack_client, random_func=random, chat=Chat(self.slack_client, "chat_chanel")) self.handler = ClueInputHandler(self.game_state) self._add_players(self.slack_client, self.game_state)
def join_chats(self, channel_url=None): if self.validate_join_chats(): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) if self.open_joining_channel(): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) # The bot update to have a link on the chats as well if self.controller.click_ok_popup_button(): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) # Get current url. It would be something like that https://t.me/Jizzax_Zomin_bozor if len(self.driver.window_handles) < 2: self.skip_channel() sleep(SLEEP_TIME_BETWEEN_COMPONENTS) self.refresh() else: self.driver.switch_to.window( self.driver.window_handles[1]) print("Bot::Current url is ", self.driver.current_url) chatUrlNameParts = self.driver.current_url.split("/") print("Bot::URL parts are", chatUrlNameParts) chatUrlName = chatUrlNameParts[len(chatUrlNameParts) - 1].strip() print("Bot::Extracted chat name", chatUrlName) self.close_tab() sleep(SLEEP_TIME_BETWEEN_COMPONENTS) self.open_channel(OPEN_CHAT_LINK_PART + chatUrlName) sleep(SLEEP_TIME_BETWEEN_COMPONENTS) channel_url = OPEN_CHAT_LINK_PART + chatUrlName if self.join_openned_channel(): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) else: channel_url = self.driver.current_url if self.join_openned_channel(): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) self.open_channel(BOT_LINK) sleep(SLEEP_TIME_BETWEEN_COMPONENTS) if self.click_button_by_name(["Joined"]): sleep(SLEEP_TIME_BETWEEN_COMPONENTS) if self.is_bot_joined_success() and channel_url != None: hoursUntillReward = self.get_hours_untill_reward() if hoursUntillReward != None: print("Bot::Hours untill reward '", hoursUntillReward, "'") joinDate = datetime.now() leaveDate = joinDate + timedelta( hours=hoursUntillReward) chat = Chat(channel_url, joinDate, leaveDate) self.chatsJoined.append(chat) print("Bot::Joined channel: ", chat.get_info()) self.joinedChatsCount += 1 print("Bot::You have joined ", self.joinedChatsCount, " chats in total") if self.joinedChatsCount % self.joinLimit == 0: self.change_operation(Operation.VISIT) else: self.change_operation(Operation.VISIT)