def index(request): # Validate token from Slack. token = request.GET['token'] if (token != 'RNmcnBKCdOZBfs3S7habfT85'): return JsonResponse({'text': 'ERROR: Invalid token %s' % token}) # Fetch channel if it exists, else create a new Channel object. channel_id = request.GET['channel_id'] try: channel = Channel.objects.get(channel_id=channel_id) except Channel.DoesNotExist: channel = Channel(channel_id=channel_id) channel.save() # Parse command from user. command = request.GET['text'] args = command.split(' ') if (len(args) < 1 or args[0] == 'help'): return showHelp() elif (args[0] == 'startGame'): return startGame(args, request.GET['user_name'], channel) elif (args[0] == 'makeMove'): return makeMove(args, request.GET['user_name'], channel) elif (args[0] == 'showBoard'): return showBoard(channel) else: return showHelp()
def emap_process(emap_version, emap_path): emap = open(emap_path, 'r') for index, line in enumerate(emap): if line[0] == "#": continue if len(line.split()) < 10: continue contents = line.split() crate = int(contents[1]) slot = int(contents[2]) dcc = int(contents[4]) spigot = int(contents[5]) fiber = int(contents[6]) fiber_channel = int(contents[7]) subdet = str(contents[8]) ieta = int(contents[9]) iphi = int(contents[10]) depth = int(contents[11]) channel = Channel(subdet=subdet, ieta=ieta, iphi=iphi, depth=depth, crate=crate, slot=slot, dcc=dcc, spigot=spigot, fiber=fiber, fiber_channel=fiber_channel, emap_version=emap_version, index=index) channel.save()
def fetchDataset (self): """Fetch a dataset to the list of cacheable datasets""" token = self.dataset_name.split('-')[0] try: json_info = json.loads(getURL('http://{}/ocpca/{}/info/'.format(settings.SERVER, token))) except Exception as e: logger.error("Token {} doesn not exist on the backend {}".format(token, settings.SERVER)) raise NDTILECACHEError("Token {} doesn not exist on the backend {}".format(token, settings.SERVER)) ximagesize, yimagesize, zimagesize = json_info['dataset']['imagesize']['0'] xoffset, yoffset, zoffset = json_info['dataset']['offset']['0'] xvoxelres, yvoxelres, zvoxelres = json_info['dataset']['voxelres']['0'] scalinglevels = json_info['dataset']['scalinglevels'] scalingoption = ND_scalingtoint[json_info['dataset']['scaling']] starttime, endtime = json_info['dataset']['timerange'] project_name = json_info['project']['name'] s3backend = json_info['project']['s3backend'] self.ds = Dataset(dataset_name=self.dataset_name, ximagesize=ximagesize, yimagesize=yimagesize, zimagesize=zimagesize, xoffset=xoffset, yoffset=yoffset, zoffset=zoffset, xvoxelres=xvoxelres, yvoxelres=yvoxelres, zvoxelres=zvoxelres, scalingoption=scalingoption, scalinglevels=scalinglevels, starttime=starttime, endtime=endtime, project_name=project_name, s3backend=s3backend) self.ds.save() for channel_name in json_info['channels'].keys(): channel_name = channel_name dataset_id = self.dataset_name channel_type = json_info['channels'][channel_name]['channel_type'] channel_datatype = json_info['channels'][channel_name]['datatype'] startwindow, endwindow = json_info['channels'][channel_name]['windowrange'] propagate = json_info['channels'][channel_name]['propagate'] readonly = json_info['channels'][channel_name]['readonly'] ch = Channel(channel_name=channel_name, dataset=self.ds, channel_type=channel_type, channel_datatype=channel_datatype, startwindow=startwindow, endwindow=endwindow, propagate=propagate, readonly=readonly) ch.save()
def setUp(self): user = User.objects.create(username='******') user.save() channel = Channel(creator=user) channel.save() self.queue = QueueManager(channel=channel.id)
def channel_add(): j = request.get_json() c = Channel(j) c.save() responseData = { 'channel_name': c.name, 'channel_id': c.id, } return json.dumps(responseData, indent=2)
def update_subscriptions(self): log.info('running update subscriptions') head = {'referer': 'http://' + 'www.hominem.se'} payload = { 'key': settings.APIKEY, 'part': 'snippet', 'channelId': 'UCvVx_jTHBKt0HW-iEkZnXTg', 'maxResults': '50' } nextpage = None more = True while more: try: r = requests.get( 'https://www.googleapis.com/youtube/v3/subscriptions', headers=head, params=payload) except requests.RequestException as e: log.error("Exception in requests.get when searching: " + str(e)) return subscriptions = json.loads(r.text) if 'nextPageToken' in subscriptions: nextpage = subscriptions['nextPageToken'] payload['pageToken'] = nextpage more = True else: nextpage = None more = False existing_subs = Channel.objects.all() log.info('Got ' + str(len(subscriptions['items'])) + ' subscriptions') for sub in subscriptions['items']: s = sub['snippet'] title = s['title'] channelId = s['resourceId']['channelId'] publishedAt = timezone.datetime.strptime( s['publishedAt'], '%Y-%m-%dT%H:%M:%S.%fZ') pub = timezone.make_aware(publishedAt, timezone=None) description = s['description'] thumb = s['thumbnails']['default']['url'] channels = Channel.objects.filter(title_text=title) if len(channels) == 0: q = Channel(channel_id=channelId, title_text=title, description_text=description, thumbnail=thumb, pub_date=pub, latest_video=pub) q.save() log.info("Added new channel: " + title) else: log.info("Channel " + title + "already exists")
def channel_add(): user = current_user() is_admin = is_administrator(user) log('Is admin? ', is_admin) if is_admin: j = request.json c = Channel(j) c.save() responseData = { 'channel_name': c.name, 'channel_id': c.id, } return json.dumps(responseData, indent=2) else: abort(401)
def channel_compile(update, context, user, text) -> str: """ Handler: fsm:2.1 -> ___ """ language = user.settings.language state = user.settings.fsm_state # TODO: don't use a context menu -> takes too long to start up. # use client.start() at initializiation. with client: # TODO: make sure the client doesn't get Floodwaited.. # If more accounts (i.e. clients) are to be used, there needs to be # an efficient way to distribute the load. try: channel = client.get_chat(text) except BadRequestPyro: # raised if username isn't occupied return txt['CALLBACK']['error_channel'][language] if channel.type != 'channel': return txt['CALLBACK']['error_channel'][language] last_message_id = client.get_history(chat_id=channel.id, limit=1)[0].message_id try: db_channel = Channel(channel_id=channel.id, username=text, last_entry_id=last_message_id, title=channel.title, description=channel.description).save() except errors.NotUniqueError: db_channel = Channel.get_channel(channel.id) if user.user_id in db_channel.subscribed: return txt['CALLBACK']['repeated_channel'][language] # adding the user to subscribed list in the channel document db_channel.subscribed.append(user.user_id) db_channel.meta_info.fetched = True db_channel.save() # adding channel to subscribed on the user document user.subscribed.channel_list.append(db_channel.pk) user.subscribed.session_list.append(db_channel.title) user.save() # format the channel looks, etc. channel_formatted = f"<a href=\"{db_channel.link}\">" + \ f"{utility.escape(channel.title)}</a>" return txt['FSM'][f'{state}b']['text'][language].format(channel_formatted)
def newchan(request): if request.method == 'POST': uc = NewChanForm(request.POST) if uc.is_valid(): cname = uc.cleaned_data['cname'] chan = Channel(name=cname, description=uc.cleaned_data['desc'], publish=[request.user.username,], subscribe=[request.user.username,], creator=request.user) #request.user.publish.append(cname) #request.user.subscribe.append(cname) chan.save() #request.user.save() return render_to_response('chancreated.html', {'cname': cname}, context_instance=RequestContext(request)) else: return render_to_response('chancreate.html', {'form': uc}, context_instance=RequestContext(request)) uc = NewChanForm() return render_to_response('chancreate.html', {'form': uc}, context_instance=RequestContext(request))
def add_channel(self, channel_id): #GET https://www.googleapis.com/youtube/v3/channels?part=snippet&id=UCskcws9RtJPRM02UVe43BQA&key={YOUR_API_KEY} head = {'referer': 'http://' + 'www.hominem.se'} payload = {'key': settings.APIKEY, 'part': 'snippet', 'id': channel_id} try: log.info("sending request") r = requests.get('https://www.googleapis.com/youtube/v3/channels', headers=head, params=payload) data = json.loads(r.text) log.info("got result " + str(data)) if 'items' not in data: log.error("bad channel id?") return for channel in data['items']: log.info("Channel data: " + str(channel)) if channel['kind'] != 'youtube#channel': log.error('kind is not youtube channel') continue s = channel['snippet'] title = s['title'] channelId = channel_id publishedAt = timezone.datetime.strptime( s['publishedAt'], '%Y-%m-%dT%H:%M:%S.%fZ') pub = timezone.make_aware(publishedAt, timezone=None) description = s['description'] thumb = s['thumbnails']['default']['url'] channels = Channel.objects.filter(title_text=title) if len(channels) == 0: q = Channel(channel_id=channelId, title_text=title, description_text=description, thumbnail=thumb, pub_date=pub, latest_video=pub) q.save() log.info("Added new channel: " + title) self.update_videos(q) else: log.info("Channel " + title + "already exists") except requests.RequestException as e: log.error("Exception in requests.get when searching: " + str(e)) return
def _get_new_posts(self, channel: Channel) -> list: """ Grabs all the new posts from a channel :param channel: document from the Channel collection :return: a list of messages (posts) """ # ensure the channel is resolved # TODO: this might need to be improved due to flood limits. _ = self.client.get_chat(channel.username) last_message_id = self.client.get_history(chat_id=channel.channel_id, limit=1)[0].message_id if last_message_id == channel.last_entry_id: return [] posts = [] # prevents from users flooding the bot, so we just grab at most last # 15 messages from the channel. for message in self.client.iter_history(channel.channel_id, limit=15): if message.message_id <= channel.last_entry_id: break posts.append(message) # the list needs to be reversed as posts go from new to old, and # users need to be served chronologically. posts.reverse() # update the last_message_id as new data has been fetched. channel.last_entry_id = last_message_id channel.save() return posts
def insertChannel(ytUserID_, tags_, comment_): ytUserID_ = ytUserID_ #attempt to change username to channel ID client = build(API_SERVICE_NAME, API_VERSION, developerKey=DEVELOPER_KEY) results = client.channels().list(part="snippet,contentDetails,statistics", forUsername=ytUserID_).execute() responseList = results.get('items', []) if len(responseList) > 0: ytUserID_ = responseList[0]['id'] try: URL = "https://socialblade.com/youtube/channel/" + ytUserID_ req = requests.get(URL) soup = BeautifulSoup(req.text, 'html.parser') ##SCRAPE ytURL_ = soup.find_all('a', href=True)[121]['href'] subscriberCount_ = soup.find( id="youtube-stats-header-subs").contents[0] country_ = soup.find(id="youtube-stats-header-country").contents[0] sd = soup.find_all(style="font-weight: bold;")[5].contents[0] sd = sd.replace("st", "") sd = sd.replace("nd", "") sd = sd.replace("rd", "") sd = sd.replace("th", "") startdate_ = datetime.datetime.strptime(sd, "%b %d, %Y") earnings_ = soup.find( style= "font-size: 1.4em; color:#41a200; font-weight: 600; padding-top: 20px;" ).contents[0] eList = earnings_.split("$") eList[1] = eList[1].replace(" - ", "") eList = eList[1:3] for t in range(len(eList)): if eList[t].find("K") != -1: eList[t] = 1000 * float(eList[t].replace("K", "")) elif eList[t].find("M") != -1: eList[t] = 1000000 * float(eList[t].replace("M", "")) minMonthEarnings_ = int(float(eList[0])) maxMonthEarnings_ = int(float(eList[1])) subscriberRank_ = soup.find( style= "font-size: 1.6em; color:#41a200; padding-top: 10px; font-weight: 600;" ).contents[0].replace(",", "") subscriberRank_ = int(subscriberRank_[0:len(subscriberRank_) - 2]) viewRank_ = soup.find( id="afd-header-videoview-rank").contents[0].replace(",", "") viewRank_ = int(viewRank_[0:len(viewRank_) - 2]) title_ = soup.find( style= "float: left; font-size: 1.4em; font-weight: bold; color:#333; margin: 0px; padding: 0px; margin-right: 5px;" ).contents[0] ##IF CHANNEL ALREADY IN DATABASE UPDATE IT, OTHERWISE INSERT IT if (Channel.objects(ytUserID=ytUserID_) or Channel.objects(URL=ytURL_)): channel = Channel.objects(ytUserID=ytUserID_) channel.update_one(set__title=title_) channel.update_one(set__URL=ytURL_) channel.update_one(set__socialblade=URL) channel.update_one(set__minMonthEarnings=minMonthEarnings_) channel.update_one(set__maxMonthEarnings=maxMonthEarnings_) channel.update_one(set__subscriberCount=subscriberCount_) channel.update_one(set__subscriberRank=subscriberRank_) channel.update_one(set__viewRank=viewRank_) channel.update_one(push_all__tags=tags_) if (comment_ != ""): channel.update_one(push__comments=comment_) else: # print(title_) # print(startdate_) # print(subscriberCount_) # print(country_ ) # print(URL) # print(ytURL_) # print(minMonthEarnings_) # print(maxMonthEarnings_) # print(subscriberRank_) # print(viewRank_) # init Channel object channel = Channel(title=title_, ytUserID=ytUserID_, startdate=startdate_, country=country_, URL=ytURL_, tags=tags_, comments=[comment_], socialblade=URL, minMonthEarnings=minMonthEarnings_, maxMonthEarnings=maxMonthEarnings_, subscriberRank=subscriberRank_, subscriberCount=subscriberCount_, viewRank=viewRank_) channel.save() print("entry updated/made") except (AttributeError, IndexError) as e: print("INVALID TARGET CHANNEL ID: " + ytUserID_) pass
class DreamcraftHandler(): """ DreamcraftHandler class for parsing commands and assigning execution """ def __init__(self, ctx, args): """ Command handler for .d, the Dreamcraft Bot command Parameters ---------- ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate Returns ------- DreamcraftHandler - object for processing Context object and args (list of strings in a command) """ self.ctx = ctx self.setup(ctx, args) def setup(self, ctx, args): """ Setup the Dreamcraft Handler with new args Parameters ---------- args : array(str) The arguments sent to the bot to parse and evaluate """ self.new = False if len(args) and args[0].lower() == 'new': self.new = True args = args[1:] if len(args) > 1 else args self.delete = False if len(args) and args[0].lower() == 'delete': self.delete = True args = args[1:] if len(args) > 1 else args self.args = args self.guild = ctx.guild if ctx.guild else ctx.author self.user = User().get_or_create(ctx.author.name, self.guild.name, ctx.author.discriminator, ctx.author.display_name) # The 'channel' variable can either be the name of the channel on a server or 'private' if Direct Message channel = 'private' if ctx.channel.type.name == 'private' else ctx.channel.name self.channel = Channel().get_or_create(channel, self.guild.name, self.user) # Add the user to the list of channel users if str(self.user.name) not in self.channel.users: self.channel.users.append(str(self.user.name)) self.channel.updated_by = str(self.user.id) self.channel.updated = T.now() self.channel.save() self.char = Character().get_by_id(self.user.active_character) if self.user and self.user.active_character else None self.module = self.char.category if self.char else None self.command = self.args[0].lower() self.alias_commands = [] self.func = None self.messages = [] self.image = '' def get_messages(self): """ Processes Context and args through command string parsing Returns ------- tuple(title: str, message: str) title : str The title of the response message message : str The string for the response message content image : str The string for the response message image """ try: modules = { 'Channel': ChannelCommand, 'Scenario': ScenarioCommand, 'Scene': SceneCommand, 'Character': CharacterCommand, 'Undo': UndoCommand, 'User': UserCommand, 'Zone': ZoneCommand, 'Session': SessionCommand, 'Engagement': EngagementCommand, 'Revision': RevisionCommand, 'Suggestion': SuggestionCommand } switcher = { 'cheat': CheatCommand, 'undo': UndoCommand, 'redo': UndoCommand, 'log': UndoCommand, 'l': UndoCommand, 'revision': RevisionCommand, 'rev': RevisionCommand, 'suggestion': SuggestionCommand, 'suggest': SuggestionCommand, 'user': UserCommand, 'u': UserCommand, 'alias': UserCommand, 'channel': ChannelCommand, 'chan': ChannelCommand, 'character': CharacterCommand, 'char': CharacterCommand, 'c': CharacterCommand, 'stats': CharacterCommand, 'scenario': ScenarioCommand, 'scene': SceneCommand, 's': SceneCommand, 'connect': SceneCommand, 'zone': ZoneCommand, 'z': ZoneCommand, 'session': SessionCommand, 'engagement': EngagementCommand, 'engage': EngagementCommand, 'e': EngagementCommand, 'caa': RollCommand, 'create': RollCommand, 'advantage': RollCommand, 'attack': RollCommand, 'att': RollCommand, 'defend': RollCommand, 'def': RollCommand, 'overcome': RollCommand, 'boost': RollCommand, 'takeout': RollCommand, 'out': RollCommand, 'freeinvoke': RollCommand, 'roll': RollCommand, 'r': RollCommand, 'reroll': RollCommand, 're': RollCommand, 'clear': RollCommand, 'erase': RollCommand, 'invoke': RollCommand, 'i': RollCommand, 'compel': RollCommand, 'available': RollCommand, 'avail': RollCommand, 'av': RollCommand, 'stress': CharacterCommand, 'st': CharacterCommand, 'consequence': CharacterCommand, 'con': CharacterCommand # 'assist': RollCommand, # 'concede': RollCommand } self.messages = [] self.search = str(self.args[0]) # Handle new syntax errors if 'new' in [a.lower() for a in self.args] or (self.new and (len(self.args) < 2 or self.new and len(self.args) > 0 and self.args[0] in ['h', 'help'])): return 'New', SETUP.new_help, self.image # Handle delete syntax errors if 'help' in [a.lower() for a in self.args] and (self.delete or 'delete' in [a.lower() for a in self.args]): return 'Delete', SETUP.delete_help, self.image # Handle alias commands self.get_alias() if self.alias_commands: alias_messages = [] alias_image = '' for ac in self.alias_commands: self.setup(self.ctx, tuple(ac.split(' '))) module, messages, image = self.get_messages() alias_messages.append(messages) alias_image = image if not alias_image else alias_image return 'Alias', 'COMMAND_SPLIT'.join(alias_messages), alias_image # Handle dialog answers self.get_answer() # Get image to embed self.get_image() if not self.messages: self.shortcuts() # Get the function from switcher dictionary if switcher.get(self.command, None): self.func = switcher.get(self.command, None) self.module = re.sub(r'commands\.|_command', '', self.func.__module__).title() if self.module != self.user.module: self.user.module = self.module self.user.updated_by = str(self.user.id) self.user.updated = T.now() self.user.save() # Get the function from User object if self.func is None and self.user.module in modules: self.module = self.user.module self.func = modules.get(self.module, None) self.args = (self.module.lower(),) + self.args # Get the function from Character object if self.func is None and self.module in modules: self.func = modules.get(self.module, None) self.args = (self.module.lower(),) + self.args # Log every comand base_svc.log(str(self.user.id), self.user.name, str(self.user.id), self.guild.name, 'Command', { 'command': self.command, 'module': self.module, 'args': self.args }, 'created') if self.func: # Execute the function and store the returned messages instance = self.func(ctx=self.ctx, args=self.args, guild=self.guild, user=self.user, channel=self.channel, parent=self) # Call the run() method for the command self.messages = instance.run() else: self.messages = [f'Unknown command: {self.command}'] # Warn user of missing time zone setting if not self.user.time_zone: self.messages = ['No time zone defined```css\n.d user timezone America/New_York\n.d user timezone list Europe```\n'] + self.messages # Concatenate messages and send if self.command == 'cheat': return self.module, [f'{m}\n' for m in self.messages], self.image else: return self.module, '\n'.join(self.messages), self.image except Exception as err: traceback.print_exc() # Log every error base_svc.log( str(self.user.id), self.user.name, str(self.user.id), self.guild.name, 'Error', { 'command': self.command, 'args': self.args, 'traceback': traceback.format_exc() }, 'created') return 'Oops!', 'Hey, bugs happen! We\'re working on it...' def get_alias(self): """ Check the list of user aliases for a match and prepare them for execution """ if self.user and self.user.aliases: args = self.args[1:] if len(self.args) > 1 else tuple() for a in self.user.aliases: if self.command == a: aliases = self.user.aliases[a] for alias in aliases: # Find all instances of '{}' mataches = re.finditer(r'\[\]|\[([^\]]+)\]|\(\)|\(([^\)]+)\)|\{\}|\{([^\}]+)\}', alias) for x in mataches: if len(args): alias = alias.replace(x.group(0), args[0]) args = args[1:] if len(args) > 1 else tuple() self.alias_commands.append(alias) def get_answer(self): """ Check for an answer if a dialog has been recorded in the user's record A dialog records the original command, the question string, and the answer. The command will track the previous command that started the dialog. The question will store the current state of the dialog. The answer is stored for processing by the command handler. """ guild = self.ctx.guild if self.ctx.guild else self.ctx.author self.user = User().find(self.ctx.author.name, guild.name) if self.user and self.user.command: answer = ' '.join(self.args[0:]) self.args = tuple(self.user.command.split(' ')) if len(self.args) and self.args[0].lower() == 'new': self.new = True self.args = self.args[1:] if len(self.args) and self.args[0].lower() == 'delete': self.delete = True self.args = self.args[1:] self.command = self.args[0].lower() self.user.answer = answer self.user.updated_by = str(self.user.id) self.user.updated = T.now() self.user.save() def get_image(self): """ Check for an action that should include an image to embed """ image_switcher = { 'caa': SETUP.action_caa_image, 'create': SETUP.action_caa_image, 'advantage': SETUP.action_caa_image, 'attack': SETUP.action_attack_image, 'att': SETUP.action_attack_image, 'defend': SETUP.action_defend_image, 'def': SETUP.action_defend_image, 'overcome': SETUP.action_overcome_image } self.image = image_switcher.get(self.command, '') def shortcuts(self): """ Check for standard approach names and skill names to update the active character Approach and skill names must be completely spelled out in order to trigger the shortcut feature. """ # shortcut for updating approaches on a character (must enter full name) approach = [s for s in APPROACHES if self.search.lower() == s.split(' - ')[0].lower()] if len(self.args) > 0 else None if approach: self.command = 'c' self.args = ('c', 'app', approach[0].split(' - ')[0]) + (self.args[1:] if len(self.args) > 1 else tuple()) # shortcut for updating skills on a character (must enter full name) skill = [s for s in SKILLS if self.search.lower() == s.split(' - ')[0].lower()] if len(self.args) > 0 else None if skill: self.command = 'c' self.args = ('c', 'sk', skill[0].split(' - ')[0]) + (self.args[1:] if len(self.args) > 1 else tuple())
def channel_new(): c = Channel(request.form) c.save() # print('channel_new: ', c) return render_template('new_channel.html')