def add_channel(update, context): temp = update.message.reply_text('لطفا صبر کنید...') try: channel_sent_list = update.effective_message.text.split('\n') except ValueError: update.message.reply_text('ورودی اشتباه') return ADD_CHANNELS channel_store_list = [] for channel in Channel.get_all(): channel_store_list.append(channel.username) for username in channel_sent_list: if username.__contains__('t.me') or username.__contains__( 'telegram.me'): try: username = '******' + \ re.search(r'\/\w{5,}', username).group(0).replace('/', '') except Exception: continue if username not in channel_store_list: channel_name = get_channel_name(username) if channel_name: Channel(username=username, name=channel_name.get_text()).add() else: update.message.reply_text( 'کانال {} وجود ندارد'.format(username)) update.message.bot.edit_message_text( chat_id=update.message.chat_id, message_id=temp.message_id, text='اکنون /done را برای ذخیره سازی کانال ها ارسال کنید') return ADD_CHANNELS
class MessagesCatcher(tornado.websocket.WebSocketHandler): def __init__(self, *args, **kwargs): super(MessagesCatcher, self).__init__(*args, **kwargs) def open(self, channel): #logging.info("opened connection") self.board_name = 'board:' + channel publisher.subscribe(self.board_name, self.on_new_board_message) self.channel = Channel(self.board_name) # when client connects send all commands written for cmd in iter(self.channel.get_commands()): self.write_message(cmd) def on_new_board_message(self, result): """ called when other client draws """ # publish in the channel try: self.write_message(result) except IOError as e: # when client closes the page websocket is not closed # but connection do, so unsuscribe from channel self.close() def on_message(self, result): """ client message with draw command """ # publish to other clients publisher.publish(self.board_name, result) self.channel.add_command(result) def close(self): publisher.unsubscribe(self.board_name, self.on_new_board_message) try: super(MessagesCatcher, self).close() except IOError: pass # java rocks
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 delete_scene(self, args, guild, channel, scenario, sc, user): messages = [] search = '' if len(args) == 1: if not sc: raise Exception('No scene provided for deletion') else: search = ' '.join(args[1:]) sc = Scene().find(guild.name, str(channel.id), str(scenario.id), search) if not sc: return [f'{search} was not found. No changes made.'] else: search = str(sc.name) scenario_id = str(sc.scenario_id) if sc.scenario_id else '' channel_id = str(sc.channel_id) if sc.channel_id else '' sc.character.archive(user) sc.archived = True sc.updated_by = str(user.id) sc.updated = T.now() sc.save() messages.append(f'***{search}*** removed') if scenario_id: secenario = Scenario().get_by_id(scenario_id) messages.append(secenario.get_string(channel)) elif channel_id: channel = Channel().get_by_id(channel_id) messages.append(channel.get_string()) return messages
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 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()
async def new_channel(self, ctx, limit: int = 0): """ Creates a new voice channel. This command creates a new voice channel for the user to use with friends. They can specify how many people should be limited to the channel. """ category = discord.utils.get(ctx.guild.categories, name='Private Channels') if category is None: await ctx.send("I couldn't find the required category, " "please contact an admin.") return if Channel.where('creator_id', ctx.author.id).first(): await ctx.send("You already have a channel! " "If you believe this is an error then " "please contact an admin.") else: channel = await ctx.guild.create_voice_channel(ctx.author.name + "'s Channel", category=category, user_limit=limit) Channel.create(id=channel.id, creator_id=ctx.author.id, voice=True) await ctx.send("Successfully made you a new channel!")
def on_join(self, channel_name): if not channel_name.startswith('#'): emit('error', {'message': 'Channel name should start with a #'}) return channel = Channel.get(channel_name) if current_user.is_authenticated: if channel is None: channel = Channel(channel_name) db.session.add(channel) if channel not in current_user.channels: current_user.channels.append(channel) join_room(channel_name) current_user.last_channel = channel db.session.commit() data = { 'channel': { 'name': channel_name }, 'user': current_user.name } else: if channel is None: data = {'channel': None} else: join_room(channel_name) data = {'channel': {'name': channel_name}} emit('channel-joined', data, room=channel_name, include_self=True)
def initChannel(userid): #Refreshes the channel api chan = Channel.get_by_key_name(userid) if not chan: chan = Channel(key_name = userid) chan.token = channel.create_channel(userid, duration_minutes=5) chan.put() return chan.token
def open(self, channel): #logging.info("opened connection") self.board_name = 'board:' + channel publisher.subscribe(self.board_name, self.on_new_board_message) self.channel = Channel(self.board_name) # when client connects send all commands written for cmd in iter(self.channel.get_commands()): self.write_message(cmd)
def setUp(self): user = User.objects.create(username='******') user.save() channel = Channel(creator=user) channel.save() self.queue = QueueManager(channel=channel.id)
def __init__(self): self.players = [] self.history = [] self.channel = Channel('game') self.turn = random.randint(0, 1) self.started = False
def get(self): outlets = Outlet.all().filter('target =', self.account).fetch(100) if len(self.request.path.split('/')) > 2: source = Account.get_by_hash(self.request.path.split('/')[-1]) channel = Channel.get_by_source_and_target(source, self.account) self.render('templates/source.html', locals()) else: enabled_channels = Channel.get_all_by_target(self.account).order('-count').filter('status =', 'enabled') self.render('templates/sources.html', locals())
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 get(self): global is_modified is_modified = True for ch in Channel.all(): ch.delete() for c in CHANNELS_LIST: channel = Channel(img_url=c["img_url"], name=c["name"]) channel.put() taskqueue.add(url="/tvfeed/update", method="POST", params={"key": channel.key(), "gogo_id": c["c_id"]}) self.response.out.write("Started")
def next_channels(update, context): query = update.callback_query if context.user_data['current_channel_page'] == math.ceil( len(Channel.get_all()) / 25): query.answer('صفحه بعد وجود ندارد') else: query.answer() context.user_data['current_channel_page'] += 1 cp = context.user_data['current_channel_page'] channels = Channel.get_all()[(cp - 1) * 25:cp * 25] return show(update, context, channels)
def admin(): user = current_user() is_admin = is_administrator(user) log('Is admin?', is_admin) if is_admin: option_json = request.json Channel.update_roles(option_json) response_data = cid_rid_for_cookie() return json.dumps(response_data, indent=2) else: abort(401)
def add_channel(): form = ChannelForm(request.form) if request.method == 'POST' and form.validate(): channel = Channel(name = form.name.data) channel.owner_id = g.user.id db.session.add(channel) db.session.commit() return redirect(url_for('channel_view', id=channel.id)) return render_template('add_channel.html', title = 'Add channel', user = g.user, form = form)
def execute(self): channel = Channel.get(self.request.channel_id) channel.now_playing_song_id = self.request.song_id channel.song_play_time = self.request.song_play_time channel.server_start_time = (time.time() * 1000) channel.playing = True Channel.update(channel) package = SyncPackage(channel=channel) channel.push_to_all(package.data) self.response.update(package.data) self.response.update({'cmd': self.cmd_id})
def post(self, hash): hash = hash.lower() target = Account.all().filter('hash =', hash).get() if not target: target = Account.all().filter('hashes =', hash).get() source = Account.all().filter('api_key =', self.request.get('api_key')).get() channel = Channel.all().filter('target =', target).filter('source =', source).get() approval_notice = None if not channel and source and target: channel = Channel(target=target, source=source, outlet=target.get_default_outlet()) channel.put() approval_notice = channel.get_approval_notice() channel.send_activation_email() if channel: notice = Notification(channel=channel, text=strip_tags(self.request.get('text')), icon=source.source_icon) for arg in ['title', 'link', 'icon', 'sticky', 'tags']: value = strip_tags(self.request.get(arg, None)) if value: setattr(notice, arg, value) notice.put() # Increment the counter on the channel to represent number of notices sent channel.count += 1 channel.put() if channel.status == 'enabled': notice.dispatch() self.response.out.write("OK\n") elif channel.status == 'pending': self.response.set_status(202) if approval_notice: approval_notice.dispatch() self.response.out.write("OK\n") else: self.response.out.write("202 Pending approval") elif channel.status == 'disabled': self.response.set_status(202) self.response.out.write("202 Accepted but disabled") else: self.error(404) self.response.out.write("404 Target or source not found")
def request_chat(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') to_user_channel = "private-notification_user_%s" % (to_user) from_user_channel = "private-notification_user_%s" % (from_user) try: bot = User.query.filter(User.id == to_user).one() except NoResultFound: print('Error! No bot (yet).') except MultipleResultsFound: print('Error! Wait what?') try: yolo.get_model(bot.username) except: print('Error! Cannot load model!') # check if there is a channel that already exists between this two user channel = Channel.query.filter( Channel.from_user.in_([from_user, to_user]) ) \ .filter( Channel.to_user.in_([from_user, to_user]) ) \ .first() if not channel: # Generate a channel... chat_channel = "private-chat_%s_%s" % (from_user, to_user) new_channel = Channel() new_channel.from_user = from_user new_channel.to_user = to_user new_channel.name = chat_channel db_session.add(new_channel) db_session.commit() else: # Use the channel name stored on the database chat_channel = channel.name data = { "from_user": from_user, "to_user": to_user, "from_user_notification_channel": from_user_channel, "to_user_notification_channel": to_user_channel, "channel_name": chat_channel, } # Trigger an event to the other user pusher.trigger(to_user_channel, 'new_chat', data) return jsonify(data)
def add_bot(self, channel, name): channel = channel.lower() name = name.lower() try: Bot.get(Bot.name == name) except peewee.DoesNotExist: pass # this seems really unpythonic somehow else: raise KeyError('Bot already exists') try: chan_o = Channel.get(Channel.name == channel) except peewee.DoesNotExist: chan_o = Channel.create(name=channel) Bot.create(name=name, channel=chan_o)
def channel_add(): name = request.form.get("name") new_channel = Channel(name=name, slack_webhook="", user_id=flask_login.current_user.user.id, discord_webhook="", count=0, active=True) db.session.add(new_channel) db.session.commit() new_channel.code = hashids.encode(new_channel.id + 100) db.session.commit() flash("Project added successfully", "success") return redirect(url_for("channel_detail", id=new_channel.id))
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 __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for SessionCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands 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 guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- SessionCommand - object for processing session commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] self.guild = guild self.user = user self.command = self.args[0].lower() if len(self.args) > 0 else 'n' channel = 'private' if ctx.channel.type.name == 'private' else ctx.channel.name self.channel = Channel().get_or_create(channel, self.guild.name, self.user) self.scenario = Scenario().get_by_id( self.channel.active_scenario ) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id( self.channel.active_scene ) if self.channel and self.channel.active_scene else None self.session = Session().get_by_id( self.channel.active_session ) if self.channel and self.channel.active_session else None self.can_edit = self.user.role == 'Game Master' if self.user and self.session else True self.char = Character().get_by_id( self.user.active_character ) if self.user and self.user.active_character else None
def UpdateChannelStats(self): """Recompute num_members for a channel.""" channel = Channel.ChannelByName(self.request.get('channel'), create=False) if not channel: return # channel became empty? num_members = int(self.request.get('num_members', '0')) q = Person.all(keys_only=True).filter('channel =', channel).order('__key__') start_at = self.request.get('start_at') if start_at: q.filter('__key__ >', db.Key(start_at)) people = q.fetch(self._STATS_BATCH) if people: # More to go. num_members += len(people) params = { 'channel': channel.name, 'num_members': num_members, 'start_at': str(people[-1]), } taskqueue.Task(url='/task/update-channel-stats', params=params).add('stats') return # Finished channel.num_members = num_members channel.put() logging.debug('%s now has %d members.' % (channel, num_members))
def names_command(self, msg): """Handle /names commands.""" m = re.match(r'^(#(?P<channel>' + Channel.CHANNEL_NAME_REGEX + '))?$', msg.arg) if not m: msg.reply('* Bad /names syntax') return if m.group('channel'): channel = Channel.ChannelByName(m.group('channel'), create=False) if not channel: msg.reply('* No such channel: #%s' % m.group('channel')) return else: channel = self.person.channel if not channel: msg.reply( '* You either need to be in a channel, or specify one.') return q = Person.all().filter('channel =', channel) people = q.fetch(self._NAME_LIMIT + 1) if len(people) <= self._NAME_LIMIT: people = people[0:self._NAME_LIMIT] names = sorted([str(p) for p in people]) msg.reply('* Members of %s: %s' % (channel, ' '.join(names))) else: msg.reply('* More than %d people in %s' % (self._NAME_LIMIT, channel))
def list_command(self, msg): """Handle /list commands.""" lines = [] q = Channel.all().order('-num_members').filter('num_members >', 0) channels = q.fetch(self._LIST_LIMIT + 1) if not len(channels): msg.reply('* No channels exist!') return if len(channels) <= self._LIST_LIMIT: # Show all, sorted by channel name. channels.sort(key=lambda c: c.name) lines.append('* All channels:') else: # Show the top N channels, sorted by num_members. channels.pop() lines.append( '* More than %d channels; here are the most popular:' % self._LIST_LIMIT) for c in channels: if c.num_members == 1: count = '1 person' else: count = '%d people' % c.num_members s = '* - %s (%s)' % (c, count) lines.append(s) msg.reply('\n'.join(lines))
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))
async def nudge_channel(message, stripped, preferences): time_parser = TimeExtractor(stripped, preferences.timezone) try: t = time_parser.extract_displacement() except InvalidTime: await message.channel.send(embed=discord.Embed( description=preferences.language.get_string('nudge/invalid_time'))) else: if 2 ** 15 > t > -2 ** 15: channel, _ = Channel.get_or_create(message.channel) channel.nudge = t session.commit() await message.channel.send( embed=discord.Embed(description=preferences.language.get_string('nudge/success').format(t))) else: await message.channel.send( embed=discord.Embed(description=preferences.language.get_string('nudge/invalid_time')))
def channel(channel_name): new_channel_form = NewChannelForm() new_post_form = NewPostForm() if request.method == "POST": if new_channel_form.submit.data and new_channel_form.validate_on_submit( ): channel = Channel(name=new_channel_form.channel_name.data) db.session.add(channel) db.session.commit() new_channel_form.channel_name.data = "" return redirect(url_for("channel", channel_name=channel_name)) elif new_post_form.submit.data and new_post_form.validate_on_submit(): post = Post(body=new_post_form.post_body.data, timestamp=datetime.utcnow(), user_id=current_user.id, channel_id=Channel.query.filter_by( name=channel_name).first().id) db.session.add(post) db.session.commit() new_post_form.post_body.data = "" return redirect(url_for("channel", channel_name=channel_name)) channels = Channel.query.all() if not any(channel_name == channel.name for channel in channels): return redirect(url_for("channels")) cur_channel = Channel.query.filter_by(name=channel_name).first() posts = cur_channel.posts return render_template("channel.html", new_channel_form=new_channel_form, new_post_form=new_post_form, channels=channels, posts=posts)
def send(event, message): from models import Channel for channel in Channel.query(): channel.send({ 'event': event, 'data': message })
def post(self, *args, **kwargs): db_connection = self.get_db_connection() already_joined = True channel_repo = ChannelRepository(db_connection) channel_name = self.get_argument('channel') channel = yield channel_repo.filter({'name': channel_name}) if not channel: channel = Channel(name=channel_name) yield channel_repo.save(channel) channel_user_repo = ChannelUserRepository(db_connection) channel_user = yield channel_user_repo.filter({ 'user': self.current_user, 'channel': channel }) if not channel_user: already_joined = False channel_user = ChannelUser(channel=channel, user=self.current_user, admin=True) yield channel_user_repo.save(channel_user) message_text = '{} has subscribed to the channel'.format( self.current_user.name) message = Message(channel=channel, text=message_text) message_repo = MessageRepository(db_connection) yield message_repo.save(message) yield message_repo.publish_message(message) yield self.release_db_connection(db_connection) self.write_json_response({ 'status': True, 'channel': { 'name': channel.name, 'id': channel.id, 'already_joined': already_joined, } })
def populate(): q=Channel.gql("WHERE id=:1", 'koan') channel=q.get() code=""" __author__ = 'peter' from application import settings import logging MSG_TYPE_TEXT = u'text' MSG_TYPE_LOCATION = u'location' MSG_TYPE_IMAGE = u'image' def process_text(remark, retort): if remark['content']: retort['content']='Bot Spawned!' retort['msgType']=MSG_TYPE_TEXT retort['funcFlag']=0 return retort def process_location(remark, retort): return retort def process_image(remark, retort): return retort """ bot=Bot(name=u'spawn', code=code, channel=channel.key) bot.put() return 'populated.'
def get(self): outlets = Outlet.all().filter("target =", self.account).fetch(100) if len(self.request.path.split("/")) > 2: source = Account.get_by_hash(self.request.path.split("/")[-1]) channel = Channel.get_by_source_and_target(source, self.account) self.render("templates/source.html", locals()) else: enabled_channels = Channel.get_all_by_target(self.account).order("-count").filter("status =", "enabled") # TODO: remove me after a while. this is to fix my poor reference management for c in enabled_channels: try: c.outlet except: c.outlet = None c.put() self.render("templates/sources.html", locals())
def fetch_new_questions(): res = '' channels = Channel.query().fetch(Channel.MAXIMUM_CHANNELS_NUMBER) for c in channels: c.fetch_new_questions() res += u'Channel: {}<br/>{}<br/>'.format(c.title, c.data) return res
def setupChannels(self): cfg = configparser.ConfigParser() cfg.read("config/channels.ini") for section in cfg.sections(): validToken = False while not validToken: try: channel = Channel.Channel(int(section), self._helix, self) for option in cfg.options(section): category = Category.Category(option, section) emoteList = cfg[section][option].split(",") for emote in emoteList: category.addEmote(emote) channel.addCategory(category) self.addChannel(channel) validToken = True except requests.exceptions.HTTPError as http_err: statusCode = http_err.response.status_code if statusCode == 401: print( "401 Unauthorized error, refreshing access token") self.refreshToken() else: print("Other error received:", statusCode) break self.hasChannels = True
def post(self, channelid): """Handles a POST to the /channel/{id}/subscriber/ resource which is to add a subscriber to the channel """ # Get channel first channel = Channel.get_by_id(int(channelid)) if channel is None: self.response.out.write("Channel %s not found" % (channelid, )) self.response.set_status(404) return # Add subscriber name = self.request.get('name').rstrip('\n') resource = self.request.get('resource').rstrip('\n') subscriber = Subscriber() subscriber.channel = channel subscriber.name = name subscriber.resource = resource subscriber.put() # Not sure I like this ... re-put()ing if len(subscriber.name) == 0: subscriber.name = 'subscriber-' + str(subscriber.key().id()) subscriber.put() # If we've got here from a web form, redirect the user to the # channel subscriber resource, otherwise return the 201 if self.request.get('subscribersubmissionform'): self.redirect(self.request.path_info) else: self.response.headers['Location'] = self.request.url + str(subscriber.key().id()) + '/' self.response.set_status(201)
def list_command(self, msg): """Handle /list commands.""" lines = [] q = Channel.all().order('-num_members').filter('num_members >', 0) channels = q.fetch(self._LIST_LIMIT + 1) if not len(channels): msg.reply(u'* 沒有任何頻道!') return if len(channels) <= self._LIST_LIMIT: # Show all, sorted by channel name. channels.sort(key=lambda c: c.name) lines.append('* 所有頻道清單如下:') else: # Show the top N channels, sorted by num_members. channels.pop() lines.append('* 頻道數超過 %d; 底下是最受歡迎的清單:' % self._LIST_LIMIT) for c in channels: if c.num_members == 1: count = '1 個人' else: count = '%d 個人' % c.num_members s = '* - %s (%s)' % (c, count) lines.append(s) msg.reply(u'\n'.join(lines))
def post(self): body = self.check_body(['title', 'base64_img']) logging.debug('called') try: channel = Channel.query(Channel.title == body['title']).get() logging.info(body) if channel: channel.put() self.response.out.write(channel.key.id()) else: channel_id = Channel.create(title=body['title'], base64_img=body['base64_img']) self.response.out.write(channel_id) except ValueError as e: self.abort(code=404, detail=e.message)
def create_channel(): req = request.get_json() name = req['name'] creator = current_user # Check if the creator has created a channel with that name before bad_name = str.strip(name.lower()) in [channel.name.lower() for channel in creator.channels] if bad_name: return jsonify( { 'success': False, 'error': 'Channel name already exisits for this user' } ) new_channel = Channel(name=name, creator=creator) db.session.add(new_channel) db.session.commit() socketio.emit('new channel', { 'name': name, 'creator': current_user.username }, broadcast=True ) return jsonify( { 'success': True, } )
def decorated_view(*args, **kwargs): channel=kwargs['channel'] channel=Channel.gql("WHERE id = :1", channel).get() if channel: kwargs['channel']=channel return func(*args, **kwargs) return redirect(url_for('qq.list_channels'))
def list_command(self, msg): """Handle /list commands.""" lines = [] q = Channel.all().order('-num_members').filter('num_members >', 0) channels = q.fetch(self._LIST_LIMIT + 1) if not len(channels): msg.reply('* No channels exist!') return if len(channels) <= self._LIST_LIMIT: # Show all, sorted by channel name. channels.sort(key=lambda c: c.name) lines.append('* All channels:') else: # Show the top N channels, sorted by num_members. channels.pop() lines.append('* More than %d channels; here are the most popular:' % self._LIST_LIMIT) for c in channels: if c.num_members == 1: count = '1 person' else: count = '%d people' % c.num_members s = '* - %s (%s)' % (c, count) lines.append(s) msg.reply('\n'.join(lines))
def new_channel(): """Create a new channel""" if request.method == 'POST': error = None # Get user input channel_name = request.form.get('channel_name') # Form validation if not channel_name: error = 'Enter channel name' elif channel_name in channels.keys(): error = 'Channel already exists' # Create channel if no error if error is None: ch = Channel(channel_name) channels[f'{channel_name}'] = ch return redirect(url_for('index')) # Display error in form flash(error) return render_template('new_channel.html')
def _initialize_channels_and_users(self): self.info('Loading channels and users...') channel_id_to_name_map, channel_name_to_id_map = \ self.slack.channel_id_name_maps() with self.database_manager.transaction(): for k, v in channel_id_to_name_map.items(): is_direct = True if k.startswith('D0') else False try: channel = Channel.get( Channel.slack_id == k ) channel.slack_name = v channel.is_direct = is_direct channel.save() except Channel.DoesNotExist: channel = Channel.create( slack_name=v, slack_id=k, is_direct=is_direct ) except Exception as e: self.error(e) channel_members = self.slack.channel_members(channel.slack_name) for channel_member in channel_members: is_slackbot = True if channel_member[1] == 'USLACKBOT' else False try: user = User.get( User.slack_name == channel_member[1], User.slack_id == channel_member[0], User.is_slackbot == is_slackbot ) except User.DoesNotExist: user = User.create( slack_name=channel_member[1], slack_id=channel_member[0], is_slackbot=is_slackbot ) except Exception as e: self.error(e) try: ChannelUserRelationship.create( channel=channel, user=user ) except: pass
def list_channels(): """List all channels""" channels = Channel.query() form = ChannelForm() if form.validate_on_submit(): channel = Channel( id = form.id.data, name = form.name.data, token = form.token.data, ) try: channel.put() flash(u'Channel %s successfully saved.' % channel.id, 'success') return redirect(url_for('qq.list_channels')) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('qq.list_channels')) return render_template('list_channels.html', channels=channels, form=form)
def get(self, op): if op == 'channels': channels = Channel.all().order('-num_members').fetch(self._MAX_CHANNELS) self.Render('channels.html', { 'channels': channels, 'max': min(len(channels), self._MAX_CHANNELS), }) elif op == 'transcript': self.RenderTranscript()
def get(self, server, channel): key = db.Key.from_path(Channel.kind(), '%s/%s' % (unquote(channel), server)) channel = Channel.get(key) date = self.request.GET.get('date') if date: start_date = datetime.strptime(date, '%Y-%m-%d').date() else: start_date = datetime.utcnow().date() end_date = start_date + timedelta(days=1) messages = Message.all().filter('channel =', channel) \ .filter('timestamp >= ', start_date) \ .filter('timestamp < ', end_date) \ .order('timestamp') # date based pagination next_day = start_date + timedelta(days=1) if next_day > datetime.utcnow().date(): next_day = None previous_day = end_date - timedelta(days=2) self.response.out.write(render('templates/channel.html', locals()))
def get_channel(self, name): """ Get channel information :param name: name of the channel """ data = self._get('channels/{0}'.format(name)) channel = Channel.object_from_dict(data) return channel
def updateInfo(key, gogo_id): channel = Channel.get(key) programs = list(Program.gql("WHERE channel = :channel", channel = channel)) for p in programs: p.delete() for day in range(1,8): #iterate week logging.info('updating info of ' + channel.name) try: updatePrograms(channel, day, gogo_id) except Exception, e: logging.error('error happened, while updating: ' + e.message)
def create_channel(session, station_id, client_id=None, name="TestChannel"): channel = Channel() channel.station_id = station_id channel.name = name channel.ecc_id = 159 channel.frequency = "00917" channel.pi = "C00F" channel.type_id = "fm" if client_id: channel.fk_client = client_id session.add(channel) session.commit() time.sleep(config.SPI_GENERATION_INTERVAL * 3) return channel
def post(self, hash): hash = hash.lower() target = Account.all().filter("hash =", hash).get() if not target: target = Account.all().filter("hashes =", hash).get() source = Account.all().filter("api_key =", self.request.get("api_key")).get() channel = Channel.all().filter("target =", target).filter("source =", source).get() approval_notice = None if not channel and source and target: channel = Channel(target=target, source=source, outlet=target.get_default_outlet()) channel.put() approval_notice = channel.get_approval_notice() channel.send_activation_email() if channel: notice = Notification(channel=channel, text=strip_tags(self.request.get("text")), icon=source.source_icon) for arg in ["title", "link", "icon", "sticky", "tags"]: value = strip_tags(self.request.get(arg, None)) if value: setattr(notice, arg, value) notice.put() # Increment the counter on the channel to represent number of notices sent channel.count += 1 channel.put() if channel.status == "enabled": notice.dispatch() self.response.out.write("OK\n") elif channel.status == "pending": self.response.set_status(202) if approval_notice: approval_notice.dispatch() self.response.out.write("OK\n") else: self.response.out.write("202 Pending approval") elif channel.status == "disabled": self.response.set_status(202) self.response.out.write("202 Accepted but disabled") else: self.error(404) self.response.out.write("404 Target or source not found")
def post(self): hash = self.request.path.split('/')[-1] target = Account.all().filter('hash =', hash).get() if not target: target = Account.all().filter('hashes =', hash).get() source = Account.all().filter('api_key =', self.request.get('api_key')).get() channel = Channel.all().filter('target =', target).filter('source =', source).get() approval_notice = None if not channel and source and target: channel = Channel(target=target, source=source, outlet=target.get_default_outlet()) channel.put() approval_notice = channel.get_approval_notice() channel.send_activation_email() if channel: notice = Notification(channel=channel, text=strip_tags(self.request.get('text')), icon=source.source_icon) for arg in ['title', 'link', 'icon', 'sticky', 'tags']: value = strip_tags(self.request.get(arg, None)) if value: setattr(notice, arg, value) notice.put() # Increment the counter on the channel to represent number of notices sent channel.count += 1 channel.put() if channel.status == 'enabled': self.response.out.write(notice.dispatch()) elif channel.status == 'pending': self.response.set_status(202) if approval_notice: self.response.out.write(":".join([channel.outlet.hash, approval_notice.to_json()])) else: self.response.out.write("202 Pending approval") elif channel.status == 'disabled': self.response.set_status(202) self.response.out.write("202 Accepted but disabled") else: self.error(404) self.response.out.write("404 Target or source not found")
def get(self, channelid): """Handles a GET to the /channel/{id}/subscriber/submissionform resource """ channel = Channel.get_by_id(int(channelid)) if channel is None: self.response.out.write("Channel %s not found" % (channelid, )) self.response.set_status(404) return template_values = { 'channel': channel, 'channelsubscriberresource': '/channel/' + channelid + '/subscriber/', } path = os.path.join(os.path.dirname(__file__), 'subscribersubmissionform.html') self.response.out.write(template.render(path, template_values))
def start(self): self.database_manager.connect() self.database_manager.create_tables(Base) self._initialize_channels_and_users() self._create_slackotron_user() self.info('Users:') for user in User.select(): self.info(user) self.info('Channels:') for channel in Channel.select(): self.info(channel) self.plugin_manager.start_plugins() self.thread_manager.start_threads() self.dashboard_manager.start_dashboard() self.run()