def display_menu_list(self, data, action_data, mlist): menuitem = ('<item>\n' '<attribute name="action">win.%s</attribute>\n' '<attribute name="label" translatable="yes">' '%s...</attribute>\n' '</item>\n') if isinstance(mlist, (list, tuple)): i = mlist[0] idval = self.generate_id(i) data.write('<submenu>\n<attribute name="label"' ' translatable="yes">%s</attribute>\n' % html.escape(i.submenu_label)) else: i = mlist idval = self.generate_id(i) data.write(menuitem % (idval, html.escape(i.menu_label))) action_data.append((idval, self.call_back_factory(i))) if isinstance(mlist, (list, tuple)) and (len(mlist) > 1): for i in mlist[1:]: if isinstance(i, list): self.display_menu_list(data, action_data, i) else: idval = self.generate_id(i) data.write(menuitem % (idval, html.escape(i.menu_label))) action_data.append((idval, self.call_back_factory(i))) if isinstance(mlist, (list, tuple)): data.write('</submenu>\n')
async def get(self, request, entity_id=None): """Generate the RSS view XML.""" response = '<?xml version="1.0" encoding="utf-8"?>\n\n' response += '<rss>\n' if self._title is not None: response += (' <title>%s</title>\n' % escape(self._title.async_render())) for item in self._items: response += ' <item>\n' if 'title' in item: response += ' <title>' response += escape(item['title'].async_render()) response += '</title>\n' if 'description' in item: response += ' <description>' response += escape(item['description'].async_render()) response += '</description>\n' response += ' </item>\n' response += '</rss>\n' return web.Response( body=response, content_type=CONTENT_TYPE_XML, status=200)
def _attach_attribute_annotation(node, record): # Adding a node to show all attributes attributes = list( (attr_name, value) for attr_name, value in record.attributes if attr_name not in PROV_ATTRIBUTE_QNAMES ) if not attributes: return # No attribute to display # Sort the attributes. attributes = sorted_attributes(record.get_type(), attributes) ann_rows = [ANNOTATION_START_ROW] ann_rows.extend( ANNOTATION_ROW_TEMPLATE % ( attr.uri, escape(six.text_type(attr)), ' href=\"%s\"' % value.uri if isinstance(value, Identifier) else '', escape(six.text_type(value) if not isinstance(value, datetime) else six.text_type(value.isoformat()))) for attr, value in attributes ) ann_rows.append(ANNOTATION_END_ROW) count[3] += 1 annotations = pydot.Node( 'ann%d' % count[3], label='\n'.join(ann_rows), **ANNOTATION_STYLE ) dot.add_node(annotations) dot.add_edge(pydot.Edge(annotations, node, **ANNOTATION_LINK_STYLE))
def render_option(cls, value, label, mixed, **kwargs): """ Render option as HTML tag, but not forget to wrap options into ``optgroup`` tag if ``label`` var is ``list`` or ``tuple``. """ if isinstance(label, (list, tuple)): children = [] for item_value, item_label in label: item_html = cls.render_option(item_value, item_label, mixed) children.append(item_html) html = u'<optgroup label="%s">%s</optgroup>' data = (escape(value), u'\n'.join(children)) else: coerce_func, data = mixed selected = coerce_func(value) == data options = {'value': value} if selected: options['selected'] = u'selected' html = u'<option %s>%s</option>' data = (html_params(**options), escape(label)) return HTMLString(html % data)
def add(request): try: if (not RequestCheckUserCapability(request, 'moodle/ejudge_submits:comment')): raise Exception("Auth Error") author_id = RequestGetUserId(request) run_id = request.params['run_id'] user_id = request.params['user_id'] # Это XSS lines = html.escape(request.params['lines']) comment = html.escape(request.params['comment']) date = datetime.datetime.now() commentary = Comment(date=date, run_id=0, # TODO: 0 - заглушка. Новые run_id теперь кладуться в py_run_id. contest_id=0, # TODO: Теперь contest_id всегда 0. user_id=user_id, author_user_id=author_id, lines=lines, comment=comment, is_read=False, py_run_id=run_id) with transaction.manager: DBSession.add(commentary) return {"result": "ok"} except Exception as e: return {"result": "error", "message": e.__str__(), "stack": traceback.format_exc()}
def column_death_place(self, data): index = data[COLUMN_DEATH] if index != -1: try: local = data[COLUMN_EVENT][index] dr = EventRef() dr.unserialize(local) event = self.db.get_event_from_handle(dr.ref) if event: place_title = place_displayer.display_event(self.db, event) if place_title: return escape(place_title) except: return '' for event_ref in data[COLUMN_EVENT]: er = EventRef() er.unserialize(event_ref) event = self.db.get_event_from_handle(er.ref) etype = event.get_type() if (etype in [EventType.BURIAL, EventType.CREMATION, EventType.CAUSE_DEATH] and er.get_role() == EventRoleType.PRIMARY): place_title = place_displayer.display_event(self.db, event) if place_title: return "<i>%s</i>" % escape(place_title) return ""
def song_text(self, song): title = html.escape(song.title) artist = html.escape(song.artist) album = html.escape(song.album) msg = [] if song is self.current_song: song.position = self.query_position() if not song.bitrate is None: msg.append("%0dkbit/s" % (song.bitrate)) if song.position is not None and song.duration is not None: pos_str = self.format_time(song.position) msg.append("%s / %s" % (pos_str, song.duration_message)) if self.playing == False: msg.append("Paused") if self.player_status.buffer_percent < 100: msg.append("Buffering (%i%%)" % self.player_status.buffer_percent) if song.message: msg.append(song.message) msg = " - ".join(msg) if not msg: msg = " " if song.is_ad: description = "<b><big>Commercial Advertisement</big></b>\n<b>Pandora</b>" else: description = "<b><big>%s</big></b>\nby <b>%s</b>\n<small>from <i>%s</i></small>" % (title, artist, album) return "%s\n<small>%s</small>" % (description, msg)
def post_newpost(): title = bottle.request.forms.get("subject", "") post = bottle.request.forms.get("body", "") tags = bottle.request.forms.get("tags", "") cookie = bottle.request.get_cookie("session") username = sessions.get_username(cookie) # see if user is logged in if username is None: bottle.redirect("/login") if title == "" or post == "": errors = "Post must contain a title and blog entry" return bottle.template("newpost_template", dict(subject=html.escape(title, quote=True), username=username, body=html.escape(post, quote=True), tags=tags, errors=errors)) # extract tags tags = html.escape(tags) tags_array = extract_tags(tags) # looks like a good entry, insert it escaped escaped_post = html.escape(post, quote=True) # substitute some <p> for the paragraph breaks newline = re.compile('\r?\n') formatted_post = newline.sub("<p>", escaped_post) permalink = posts.insert_entry(title, formatted_post, tags_array, username) # now bottle.redirect to the blog permalink bottle.redirect("/post/" + permalink)
def column_birth_place(self, data): index = data[COLUMN_BIRTH] if index != -1: try: local = data[COLUMN_EVENT][index] br = EventRef() br.unserialize(local) event = self.db.get_event_from_handle(br.ref) if event: place_title = place_displayer.display_event(self.db, event) if place_title: return escape(place_title) except: return '' for event_ref in data[COLUMN_EVENT]: er = EventRef() er.unserialize(event_ref) event = self.db.get_event_from_handle(er.ref) etype = event.get_type() if (etype in [EventType.BAPTISM, EventType.CHRISTEN] and er.get_role() == EventRoleType.PRIMARY): place_title = place_displayer.display_event(self.db, event) if place_title: return "<i>%s</i>" % escape(place_title) return ""
def make_rss(works): def mkdate(d): format_string = "%Y-%m-%d %H:%M:%S" r = rfc822(datetime.strptime(d, format_string).timestamp()) return r now = rfc822(datetime.now().timestamp()) ver = platform.python_version() print("<?xml version=\"1.0\"?>") print("<rss version=\"2.0\">") print("<channel>") print(" <title>[pixiv] フォロー新着作品</title>") print(" <link>http://www.pixiv.net/bookmark_new_illust.php</link>") print(" <pubDate>" + now + "</pubDate>") print(" <description />") print(" <generator>pixivrss (Python " + ver + ")</generator>") for i in works: title = i['title'] + " | " + i['user']['name'] print("\n <item>") print(" <title>" + escape(title) + "</title>") print(" <link>" + escape(ILLUST_URL + str(i['id'])) + "</link>") if i['caption']: caption = escape(i['caption']).replace("\r\n", "<br />") print(" <description>" + caption + "</description>") print(" <pubDate>" + mkdate(i['created_time']) + "</pubDate>") print(" <guid>" + escape(ILLUST_URL + str(i['id'])) + "</guid>") print(" </item>") print("</channel>") print("</rss>")
def song_text(self, song): title = html.escape(song.title) artist = html.escape(song.artist) album = html.escape(song.album) msg = [] if song is self.current_song: dur_stat, dur_int = self.player.query_duration(self.time_format) pos_stat, pos_int = self.player.query_position(self.time_format) if not self.song_started: pos_int = 0 if not song.bitrate is None: msg.append("%0dkbit/s" % (song.bitrate / 1000)) if dur_stat and pos_stat: dur_str = self.format_time(dur_int) pos_str = self.format_time(pos_int) msg.append("%s / %s" %(pos_str, dur_str)) if not self.playing: msg.append("Paused") if self.buffer_percent < 100: msg.append("Buffering (%i%%)"%self.buffer_percent) if song.message: msg.append(song.message) msg = " - ".join(msg) if not msg: msg = " " if song.is_ad: description = "<b><big>Commercial Advertisement</big></b>\n<b>Pandora</b>" else: description = "<b><big>%s</big></b>\nby <b>%s</b>\n<small>from <i>%s</i></small>" % (title, artist, album) return "%s\n<small>%s</small>" % (description, msg)
def _on_message(self, client, conv_id, user_id, timestamp, text): """Create notification for new messages.""" conv = self._conv_list.get(conv_id) user = conv.get_user(user_id) # Ignore messages sent by yourself. if not user.is_self: # We have to escape angle brackets because freedesktop.org # notifications support markup. cmd = [arg.format( sender_name=html.escape(user.full_name, quote=False), msg_text=html.escape(text, quote=False), replaces_id=self._replaces_id, ) for arg in NOTIFY_CMD] # Run the notification and parse out the replaces_id. Since the # command is a list of arguments, and we're not using a shell, this # should be safe. logger.info('Creating notification with command: {}'.format(cmd)) try: output = subprocess.check_output( cmd, stderr=subprocess.STDOUT ).decode() except (subprocess.CalledProcessError, FileNotFoundError) as e: logger.warning('Notification command failed: {}'.format(e)) return try: self._replaces_id = RESULT_RE.match(output).groups()[0] except (AttributeError, IndexError) as e: logger.warning('Failed to parse notification command ' 'result: {}'.format(e))
def _write_output(self, test_results): junit_output = self.options["junit_output"] with io.open(junit_output, mode="w", encoding="utf-8") as f: f.write(u'<testsuite tests="{}">\n'.format(len(test_results))) for result in test_results: s = ' <testcase classname="{}" name="{}"'.format( result["ClassName"], result["Method"] ) if ( "Stats" in result and result["Stats"] and "duration" in result["Stats"] ): s += ' time="{}"'.format(result["Stats"]["duration"]) if result["Outcome"] in ["Fail", "CompileFail"]: s += ">\n" s += ' <failure type="failed" ' if result["Message"]: s += 'message="{}"'.format(html.escape(result["Message"])) s += ">" if result["StackTrace"]: s += "<![CDATA[{}]]>".format(html.escape(result["StackTrace"])) s += "</failure>\n" s += " </testcase>\n" else: s += " />\n" f.write(str(s)) f.write(u"</testsuite>") json_output = self.options["json_output"] with io.open(json_output, mode="w", encoding="utf-8") as f: f.write(str(json.dumps(test_results, indent=4)))
def popup_brief(self): """ Brief info on popup with name, possibly with link if have source location """ info = u'<span class="function">{0}</span>'.format(html.escape(self.name, quote = False)) if self.has_source_location(): return u'<a href="{0}">{1}</a>'.format(html.escape(self.get_source_location()), info) else: return info
def popup(self, comments = []): """ Full info on popup with docs """ parts = [u'<p>'] parts.append(self.popup_brief()) for c in comments: parts.append(u'<br>{0}<span class="comment">-- {1}</span>'.format( 4 * ' ', c)) if self.imported_names(): parts.append(u'<br>{0}<span class="comment">-- Imported from {1}</span>'.format( 4 * ' ', html.escape(u', '.join(self.imported_names()), quote = False))) if self.defined_module(): module_ref = html.escape(self.defined_module().name, quote = False) if self.defined_module().by_source(): module_ref = u'<a href="{0}">{1}</a>'.format(self.defined_module().location.to_string(), module_ref) elif self.defined_module().by_cabal(): hackage_url = 'http://hackage.haskell.org/package/{0}/docs/{1}.html'.format( self.defined_module().location.package.package_id(), self.defined_module().name.replace('.', '-')) module_ref = u'<a href="{0}">{1}</a>'.format(html.escape(hackage_url), module_ref) parts.append(u'<br>{0}<span class="comment">-- Defined in {1}</span>'.format( 4 * ' ', module_ref)) parts.append(u'</p>') if self.docs: parts.append(u'<p><span class="docs">{0}</span></p>'.format(escape_text(self.docs))) # parts.append(u'<a href="info">...</a>') return u''.join(parts)
def append_to_pdf(self, story): try: assignment_pk = self.kwargs['pk'] except KeyError: assignment_pk = None if assignment_pk is None: # print all assignments title = escape(config["assignments_pdf_title"]) story.append(Paragraph(title, stylesheet['Heading1'])) preamble = escape(config["assignments_pdf_preamble"]) if preamble: story.append(Paragraph( "%s" % preamble.replace('\r\n', '<br/>'), stylesheet['Paragraph'])) story.append(Spacer(0, 0.75 * cm)) assignments = Assignment.objects.all() if not assignments: # No assignments existing story.append(Paragraph( _("No elections available."), stylesheet['Heading3'])) else: # Print all assignments # List of assignments for assignment in assignments: story.append(Paragraph( escape(assignment.title), stylesheet['Heading3'])) # Assignment details (each assignment on single page) for assignment in assignments: story.append(PageBreak()) # append the assignment to the story-object self.get_assignment(assignment, story) else: # print selected assignment assignment = Assignment.objects.get(pk=assignment_pk) # append the assignment to the story-object self.get_assignment(assignment, story)
def test_escape(self): self.assertEqual( html.escape('\'<script>"&foo;"</script>\''), ''<script>"&foo;"</script>'') self.assertEqual( html.escape('\'<script>"&foo;"</script>\'', False), '\'<script>"&foo;"</script>\'')
def signup(): usertype = "user" json = request.get_json(force=True) name = escape(json["name"].strip()) email = json["email"].strip() if len(name) == 0: raise Exception("InvalidUserName") if len(email) == 0: raise Exception("InvalidEmailAddress") if not len(email.split("@")) == 2: raise Exception("InvalidEmailAddress") email = escape(email.strip()) # Make sure the user name is 4-25 letters/digits only. if len(name) < 4 or len(name) > 25: raise Exception("InvalidUserName") if not all([x in string.ascii_letters or x in string.digits for x in name]): raise Exception("InvalidUserName") # Check if name exists if query_db("SELECT name FROM users WHERE name=?", name): raise Exception("UserExists") if query_db("Select id, name FROM users WHERE email=?", email): raise Exception("EmailExists") # Insert user // TODO: implement the verification email db = get_db() c = db.cursor() c.execute("INSERT INTO users(name, email, type) values(?, ?, ?)", (name, email, usertype)) db.commit() return jsonify({"success": True})
def exportPl(self, speaker, pl, force, detail): """ Export playlist from speaker to an XSPF file. """ fileName = pl.title + '.xspf' if not force and os.path.isfile(fileName): print('Error: file already exists: ' + fileName) return with codecs.open(fileName, 'w', 'utf-8') as fp: fp.write('<?xml version="1.0" encoding="UTF-8"?>\n') fp.write('<playlist version="1" xmlns="http://xspf.org/ns/0/">\n') fp.write(' <title>%s</title>\n' % pl.title) fp.write(' <trackList>\n') start = 0 max_items = 100 cnt = 0 while True: trackList = speaker.browse(pl, start=start, max_items=max_items) if not trackList: break # done for item in trackList: fp.write(' <track>\n') if not detail: fp.write(' <location>%s</location>\n' % item.resources[0].uri) else: title = html.escape(item.title) fp.write(' <title>%s</title>\n' % title) creator = html.escape(item.creator) fp.write(' <creator>%s</creator>\n' % creator) album = html.escape(item.album) fp.write(' <album>%s</album>\n' % album) fp.write(' </track>\n') cnt += 1 start += max_items fp.write(' </trackList>\n') fp.write('</playlist>\n') print(pl.title + ': ' + str(cnt) + ' songs')
def write_html_report(report, args): """Write report as an html file""" # Only write the report if the html_file argument was used if report is not None: if args.html_file is not None: html_start = """<html><head><style> table { border-collapse: collapse; } table, th, td { border: 1px solid black; } </style></head><body><table>""" html_end = '</table></body></html>' table = '' # First row has headers table += '<tr>' + ''.join(['<th>' + html.escape(x) + '</th>' for x in report[0]]) + '</tr>' for row in report[1:]: table += '<tr>' for i in range(len(row)): if i == 7: val = html.escape(split_string(row[i], 30)) else: val = html.escape(str(row[i])) table += "<td valign='top'>" + val + "</td>" table += '</tr>' with open(args.html_file.strip(), 'w') as h: h.write(html_start + table + html_end)
def as_html_handle_data_algebra(mathobj): r"""Return ``mathobj`` converted into a string safe to be used in HTML. - If ``mathobj`` is a `MathObject`, it will be represented as LaTeX markup and wrapped in the mathjax escape token. - If it is a container of `MathObject`\s, then each one will be represented as LaTeX markup and displayed on its own line. - If it is not a `MathObject` then the ``str`` function will be invoked. """ if isinstance(mathobj, _mo.MathObject): # print this one math object return "$$" + _html.escape(_latexprinter.math_object_to_latex(mathobj)) + "$$" elif isinstance(mathobj, _collections.Iterable): temp = "" for elem in mathobj: if isinstance(elem, _mo.MathObject): # latex temp += r"$$\(\require{color}\)\(\require{xcolor}\)" + \ _html.escape(_latexprinter.math_object_to_latex(elem)) + "$$ <br //>" else: # str temp += _html.escape(str(elem)) + "<br //>" return temp else: # print this one non-math object using str(mathobjects) return _html.escape(str(mathobj))
def connect_form(self): form = cgi.FieldStorage() text1 = form.getfirst("Login", "empty field") text2 = form.getfirst("Password", "empty field") text1 = html.escape(text1) text2 = html.escape(text2) return (text1, text2)
def updated_edit_cell(request, field, value, proc_id): """compares the old and the new value and returns the fields that are changed """ meta_table = get_mt(request, proc_id)['doc']; updated = ''; meta = {} for res in meta_table: if field in res.get('id'): meta = res if 'type' in meta: if meta['type'] == 'passw': v = '*****'; formatted = '*****' elif meta['type'] == 'checkbox': v = str(value) if v == 'true': color = 'green'; icon = 'fa-check' else: color = 'red'; icon = 'fa-close' formatted = "<span style='color:"+color+"; font-size:16px'><i class='fa "+icon+"'></i></span>" elif meta['type'] == 'select': v = str(value) aaa = get_doc(request, v) if aaa: formatted = html.escape(get_doc_title(request, aaa, '[{}]'.format(v) )) else: formatted = '-' elif meta['type'] == 'cascad_select': v = str(value) aaa = get_doc(request, v) if aaa: formatted = html.escape(get_doc_title_cascad(request, aaa, '[{}]'.format(v) )) else: formatted = '-' else: formatted = value v = value t = type(v) if t == int or t == float or meta['type'] == 'checkbox': updated = { "formatted":formatted, "value":v, 'field_name':field } else: updated = { "formatted":formatted, "value": v, 'field_name':field } return updated
def append_log_html(self, report, additional_html): log = html.div(class_='log') if report.longrepr: for line in report.longreprtext.splitlines(): separator = line.startswith('_ ' * 10) if separator: log.append(line[:80]) else: exception = line.startswith("E ") if exception: log.append(html.span(raw(escape(line)), class_='error')) else: log.append(raw(escape(line))) log.append(html.br()) for section in report.sections: header, content = map(escape, section) log.append(' {0} '.format(header).center(80, '-')) log.append(html.br()) if ANSI: converter = Ansi2HTMLConverter(inline=False, escaped=False) content = converter.convert(content, full=False) log.append(raw(content)) if len(log) == 0: log = html.div(class_='empty log') log.append('No log output captured.') additional_html.append(log)
def write_dir_listing(indirname, outfname): lines = [] outdirname = path.dirname(outfname) try: os.remove(outfname) # Avoid self-listing. except FileNotFoundError: pass for root, dirs, files in os.walk(indirname): def file_filter(f): stemName, extName = path.splitext(f) if extName != ".html": return False if ext(stemName)[1:].lower() not in CEXTS: return False return True files = list(filter(file_filter, files)) if not files: continue files.sort() root = path.relpath(root, outdirname) lines.append('<li class="dir"><span class="dirname">{0}</span><ul>'.format(root)) for file in files: lines.append('<li class="file"><a href="{0}">{1}</a></li>' .format(escape(path.join(root, file)), escape(stem(file)))) lines.append("</ul></li>") with open(outfname, "w", encoding="utf-8") as f: f.write(OUT_TEMPLATE.format("\n".join(lines)))
def saveproject(): json = request.get_json(force=True) name = request.cookies["name"] token = request.cookies["token"] # TODO String projectId = paperbots.saveProject(ctx.cookie("token"), request.getCode(), request.getTitle(), request.getDescription(), request.getContent(), request.isPublic(), request.getType()); userId, username, email, usertype = user_by_token(token) db = get_db() c = db.cursor() if not json["code"]: project_id = random_code(6) c.execute( "INSERT INTO projects(userId, userName, code, title, description, content, public, type) " "VALUES(?,?,?,?,?,?,?,?)", (userId, username, project_id, escape(json["title"]), escape(json["description"]), json["content"], True, json["type"])) db.commit() return jsonify({"projectId": project_id}) else: c.execute("UPDATE projects SET title=?, description=?, content=?, public=? WHERE code=? AND userId=?", (escape(json["title"]), escape(json["description"]), json["content"], True, json["code"], userId) ) db.commit() return jsonify({"projectId": json["code"]})
def scan_section(line, pos): m = cs_re.search(line, pos) if not m: # no match; done print(html.escape(line[pos:], quote=False), end='') return len(line) # output up to the csi print(html.escape(line[pos:m.start()], quote=False), end='') code_string = m.group(1) codes = [] for s in code_string.split(';'): if not s: continue # splitting empty string returns empty string try: code = int(s) except ValueError: errFL('ERROR: could not parse code: {}; sequence: {}', repr(s), repr(code_string)) continue codes.append(code) #errSLD('codes:', codes) if not codes: # empty sequence is equivalent to a clear close_spans_clear() for code in codes: if code == 0: # reset close_spans_clear() continue try: class_ = codes_to_classes[code] except KeyError: errSLN('NOTICE: unrecognized SGR code:', code) continue excise_span_if_present(class_) if code not in reset_codes: open_span_push(class_) return m.end()
def ping_pong(message): arguments = message.text.split() host = arguments[1] if len(arguments) == 2 else "<INVALID-HOST>" if not host_pattern.match(host): bot.send_message(chat_id=message.chat.id, text=PING_USAGE, parse_mode="html") return # Не нравится эта идея. Надо избавиться от этой проверки в этом месте if os.system("which ping > /dev/null") != 0: bot.send_message(chat_id=message.chat.id, text=DEPENDS, parse_mode="html") return place = bot.send_message(chat_id=message.chat.id, text=WAITING) result = subprocess.getstatusoutput("LANG=ru_RU.UTF-8 ping -c5 -- {}" .format(host)) if result[0] == 2: reason = result[1].split(": ")[2] bot.edit_message_text(chat_id=message.chat.id, message_id=place.message_id, text=ERROR.format(html.escape(reason)), parse_mode="html") return bot.edit_message_text(chat_id=message.chat.id, message_id=place.message_id, text=PING_OK.format(html.escape(result[1])), parse_mode="html")
def all_motion_cover(pdf, motions): """ Create a coverpage for all motions. """ pdf.append(Paragraph(escape(config["motions_export_title"]), stylesheet['Heading1'])) preamble = escape(config["motions_export_preamble"]) if preamble: pdf.append(Paragraph("%s" % preamble.replace('\r\n', '<br/>'), stylesheet['Paragraph'])) pdf.append(Spacer(0, 0.75 * cm)) # list of categories categories = False for i, category in enumerate(Category.objects.all()): categories = True if i == 0: pdf.append(Paragraph(_("Categories"), stylesheet['Heading2'])) pdf.append(Paragraph("%s %s" % (escape(category.prefix), escape(category.name)), stylesheet['Paragraph'])) if categories: pdf.append(PageBreak()) # list of motions if not motions: pdf.append(Paragraph(_("No motions available."), stylesheet['Heading3'])) else: for motion in motions: identifier = '' if motion.identifier: identifier = ' %s' % motion.identifier pdf.append(Paragraph('%s%s: %s' % (_('Motion'), identifier, escape(motion.title)), stylesheet['Heading3']))
def __init__(self, id, extra=None, caller=None, index_factory=None, field_name=None, lexicon_id=None): self.id = id # Arguments can be passed directly to the constructor or # via the silly "extra" record. self._fieldname = field_name or getattr(extra, 'doc_attr', '') or id self._indexed_attrs = self._fieldname.split(',') self._indexed_attrs = [attr.strip() for attr in self._indexed_attrs if attr] lexicon_id = lexicon_id or getattr(extra, 'lexicon_id', '') lexicon = getattr(caller, lexicon_id, None) if lexicon is None: raise LookupError('Lexicon "%s" not found' % escape(lexicon_id)) if not ILexicon.providedBy(lexicon): raise ValueError('Object "%s" does not implement ' 'ZCTextIndex Lexicon interface' % lexicon.getId()) self.lexicon_id = lexicon.getId() self._v_lexicon = lexicon if index_factory is None: if extra.index_type not in index_types.keys(): raise ValueError('Invalid index type "%s"' % escape( extra.index_type)) self._index_factory = index_types[extra.index_type] self._index_type = extra.index_type else: self._index_factory = index_factory self.index = self._index_factory(aq_base(self.getLexicon()))
def set_flood(update, context) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if len(args) >= 1: val = args[0].lower() if val in ["off", "no", "0"]: sql.set_flood(chat_id, 0) if conn: text = message.reply_text( "Antiflood has been disabled in {}.".format(chat_name)) else: text = message.reply_text("Antiflood has been disabled.") elif val.isdigit(): amount = int(val) if amount <= 0: sql.set_flood(chat_id, 0) if conn: text = message.reply_text( "Antiflood has been disabled in {}.".format(chat_name)) else: text = message.reply_text("Antiflood has been disabled.") return ("<b>{}:</b>" "\n#SETFLOOD" "\n<b>Admin:</b> {}" "\nDisable antiflood.".format( html.escape(chat_name), mention_html(user.id, html.escape(user.first_name)), )) elif amount <= 3: send_message( update.effective_message, "Antiflood must be either 0 (disabled) or number greater than 3!", ) return "" else: sql.set_flood(chat_id, amount) if conn: text = message.reply_text( "Anti-flood has been set to {} in chat: {}".format( amount, chat_name)) else: text = message.reply_text( "Successfully updated anti-flood limit to {}!".format( amount)) return ("<b>{}:</b>" "\n#SETFLOOD" "\n<b>Admin:</b> {}" "\nSet antiflood to <code>{}</code>.".format( html.escape(chat_name), mention_html(user.id, html.escape(user.first_name)), amount, )) else: message.reply_text( "Invalid argument please use a number, 'off' or 'no'") else: message.reply_text( ("Use `/setflood number` to enable anti-flood.\nOr use `/setflood off` to disable antiflood!." ), parse_mode="markdown", ) return ""
def check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins and whitelists if is_user_admin(chat, user.id) or user.id in WOLVES or user.id in TIGERS: sql.update_flood(chat.id, None) return "" # ignore approved users if is_approved(chat.id, user.id): sql.update_flood(chat.id, None) return should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = "Banned" tag = "BANNED" elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = "Kicked" tag = "KICKED" elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False)) execstrings = "Muted" tag = "MUTED" elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = "Banned for {}".format(getvalue) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) execstrings = "Muted for {}".format(getvalue) tag = "TMUTE" send_message(update.effective_message, "Beep Boop! Boop Beep!\n{}!".format(execstrings)) return ("<b>{}:</b>" "\n#{}" "\n<b>User:</b> {}" "\nFlooded the group.".format( tag, html.escape(chat.title), mention_html(user.id, html.escape(user.first_name)), )) except BadRequest: msg.reply_text( "I can't restrict people here, give me permissions first! Until then, I'll disable anti-flood." ) sql.set_flood(chat.id, 0) return ( "<b>{}:</b>" "\n#INFO" "\nDon't have enough permission to restrict users so automatically disabled anti-flood" .format(chat.title))
async def channel_log(msg, info_log=True): chat_id = get_int_key("LOGS_CHANNEL_ID") if info_log: log.info(msg) await bot.send_message(chat_id, html.escape(msg, quote=False))
def textinput(input=None): input = escape(input) return f'You said: {input}'
def set_flood_mode(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] args = context.args conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": send_message( update.effective_message, "This command is meant to use in group not in PM", ) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if args: if args[0].lower() == "ban": settypeflood = "ban" sql.set_flood_strength(chat_id, 1, "0") elif args[0].lower() == "kick": settypeflood = "kick" sql.set_flood_strength(chat_id, 2, "0") elif args[0].lower() == "mute": settypeflood = "mute" sql.set_flood_strength(chat_id, 3, "0") elif args[0].lower() == "tban": if len(args) == 1: teks = """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tban <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""" send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = "tban for {}".format(args[1]) sql.set_flood_strength(chat_id, 4, str(args[1])) elif args[0].lower() == "tmute": if len(args) == 1: teks = ( update.effective_message, """It looks like you tried to set time value for antiflood but you didn't specified time; Try, `/setfloodmode tmute <timevalue>`. Examples of time value: 4m = 4 minutes, 3h = 3 hours, 6d = 6 days, 5w = 5 weeks.""", ) send_message(update.effective_message, teks, parse_mode="markdown") return settypeflood = "tmute for {}".format(args[1]) sql.set_flood_strength(chat_id, 5, str(args[1])) else: send_message(update.effective_message, "I only understand ban/kick/mute/tban/tmute!") return if conn: text = msg.reply_text( "Exceeding consecutive flood limit will result in {} in {}!". format(settypeflood, chat_name)) else: text = msg.reply_text( "Exceeding consecutive flood limit will result in {}!".format( settypeflood)) return ("<b>{}:</b>\n" "<b>Admin:</b> {}\n" "Has changed antiflood mode. User will {}.".format( settypeflood, html.escape(chat.title), mention_html(user.id, html.escape(user.first_name)), )) else: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: settypeflood = "ban" elif getmode == 2: settypeflood = "kick" elif getmode == 3: settypeflood = "mute" elif getmode == 4: settypeflood = "tban for {}".format(getvalue) elif getmode == 5: settypeflood = "tmute for {}".format(getvalue) if conn: text = msg.reply_text( "Sending more messages than flood limit will result in {} in {}." .format(settypeflood, chat_name)) else: text = msg.reply_text( "Sending more message than flood limit will result in {}.". format(settypeflood)) return ""
def document_body(docs: Optional[str]) -> str: """build documentation body""" return ("<p>%s</p>" % escape_newline(escape_space(escape(docs, quote=False))) if docs else "")
def textinputand(input=None): input = escape(input) q = escape(request.args.get('then', default="nothing")) return f'You said: {input} and {q}'
async def _(event): sender = await event.get_sender() me = await event.client.get_me() if not sender.id == me.id: tele = await event.reply("`Processing...`") else: tele = await event.edit("`Processing...`") if event.fwd_from: return tuser, rdhs = await get_full_user(event) if tuser is None: await tele.edit("Error! Please mention user to check his stats!!") return False user_id = tuser.user.id first_name = html.escape(tuser.user.first_name) if first_name is not None: first_name = first_name.replace("\u2060", "") user_bio = tuser.about if user_bio is not None: user_bio = html.escape(tuser.about) spamw = "SpamWatch API not added.\nGet it from @SpamWatchBot and add it to `SPAMWATCH_API_KEY` for this plugin to work." sreason = {} try: cas_url = f"https://api.cas.chat/check?user_id={user_id}" r = get(cas_url, timeout=3) data = r.json() except BaseException: pass spambot = data = None if data: if data and data["ok"]: reason = f"[Banned by Combot Anti Spam](https://combot.org/cas/query?u={check_user.id})" spambot = True if spambot: sbot = "Yes" sn = reason else: sbot = "No" sn = {} if swapi: sw = spamwatch.Client(swapi) sswatch = sw.get_ban(user_id) if sswatch: spamw = "`Yes`" sreason = sswatch.reason else: spamw = "`No`" sreason = {} caption = f"**About** [{first_name}](tg://user?id={user_id})\n\n" caption += f"**User ID:** `{user_id}`\n" caption += f"**UserName:** `@{tuser.user.username}`\n" caption += f"**Scam:** `{tuser.user.scam}`\n" caption += f"**Restricted:** `{tuser.user.restricted}`\n" temp = tuser.user.restriction_reason if temp: caption += f"**Reason:** `{temp}`\n\n" caption += f"**Banned in SpamWatch:** {spamw}\n" if sreason: caption += f"**Reason:** `{sreason}`\n\n" caption += f"**Banned in CAS:** {sbot} [?](http://cas.chat)\n" if sn: caption += f"**Reason:** `{sn}`\n\n" await tele.edit(caption)
def clean_message(msg): return html.escape(msg, quote=False).replace("%", "%%").replace( "{", "(").replace("}", ")") if msg else ""
def send_image(self, graph_paths): """Load graph and send to frontend This supports SVG, PNG, and PDF formats. While PDF display isn't supported in Atom or Jupyter, the data can be stored within the Jupyter Notebook file and makes exporting images to PDF through LaTeX easier. Args: graph_paths (List[str]): path to exported graph """ no_display_msg = 'This front-end cannot display the desired image type.' content = {'data': {'text/plain': no_display_msg}, 'metadata': {}} warn = False for graph_path in graph_paths: file_size = Path(graph_path).stat().st_size if (file_size > 2 * (1024**3)) & (len(graph_paths) >= 2): warn = True if graph_path.endswith('.svg'): with Path(graph_path).open('r', encoding='utf-8') as f: img = f.read() e = ET.ElementTree(ET.fromstring(img)) root = e.getroot() width = int(root.attrib['width'][:-2]) height = int(root.attrib['height'][:-2]) # Wrap SVG in iframe. See #234. iframe = """\ <iframe frameborder="0" scrolling="no" height="{0}" width="{1}"\ srcdoc="<html><body>{2}</body></html>"></iframe> """.format(height, width, html.escape(img)) content['data']['text/html'] = dedent(iframe) content['metadata']['text/html'] = { 'width': width, 'height': height } content['data']['image/svg+xml'] = img content['metadata']['image/svg+xml'] = { 'width': int(root.attrib['width'][:-2]), 'height': int(root.attrib['height'][:-2]) } elif graph_path.endswith('.png'): im = Image.open(graph_path) width = im.size[0] height = im.size[1] # On my Mac, the width is double what I told Stata to export. # This is not true on my Windows test VM if platform.system() == 'Darwin': width /= 2 height /= 2 with Path(graph_path).open('rb') as f: img = base64.b64encode(f.read()).decode('utf-8') content['data']['image/png'] = img content['metadata']['image/png'] = { 'width': width, 'height': height } elif graph_path.endswith('.pdf'): with Path(graph_path).open('rb') as f: pdf = base64.b64encode(f.read()).decode('utf-8') content['data']['application/pdf'] = pdf msg = """\ **`stata_kernel` Warning**: One of your image files is larger than 2MB and you have Graph Redundancy on. If you don't plan to export the Jupyter Notebook file to PDF, you can save space by running: ``` %set graph_svg_redundancy false [--permanently] %set graph_png_redundancy false [--permanently] ``` To turn off this warning, run: ``` %set graph_redundancy_warning false [--permanently] ``` For more information, see: <https://kylebarron.dev/stata_kernel/using_stata_kernel/intro/#graph-redundancy> """ msg = dedent(msg) warn_setting = config.get('graph_redundancy_warning', 'True') if warn and (warn_setting.lower() == 'true'): self.send_response(self.iopub_socket, 'display_data', { 'data': { 'text/plain': msg, 'text/markdown': msg }, 'metadata': {} }) self.send_response(self.iopub_socket, 'display_data', content)
def gban(update, context): message = update.effective_message chat = update.effective_chat args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") return if user_id == OWNER_ID: message.reply_text("Nice try -_- but I'm never gonna gban him.") return if int(user_id) in SUDO_USERS: message.reply_text( "I spy, with my little eye... a sudo user war! Why are you guys turning on each other?" ) return if user_id == context.bot.id: message.reply_text("-_- So funny, lets gban myself why don't I? Nice try.") return try: user_chat = context.bot.get_chat(user_id) except BadRequest as excp: message.reply_text(excp.message) return if user_chat.type != "private": message.reply_text("That's not a user!") return if user_chat.first_name == "": message.reply_text("This is a deleted account! no point to gban them...") return if sql.is_user_gbanned(user_id): if not reason: message.reply_text( "This user is already gbanned; I'd change the reason, but you haven't given me one..." ) return old_reason = sql.update_gban_reason( user_id, user_chat.username or user_chat.first_name, reason ) user_id, new_reason = extract_user_and_text(message, args) if old_reason: banner = update.effective_user # type: Optional[User] bannerid = banner.id bannername = banner.first_name new_reason = ( f"{new_reason} // GBanned by {bannername} banner id: {bannerid}" ) context.bot.sendMessage( MESSAGE_DUMP, "<b>Global Ban Reason Update</b>" "\n<b>Sudo Admin:</b> {}" "\n<b>User:</b> {}" "\n<b>ID:</b> <code>{}</code>" "\n<b>Previous Reason:</b> {}" "\n<b>New Reason:</b> {}".format( mention_html(banner.id, banner.first_name), mention_html( user_chat.id, user_chat.first_name or "Deleted Account" ), user_chat.id, old_reason, new_reason, ), parse_mode=ParseMode.HTML, ) message.reply_text( "This user is already gbanned, for the following reason:\n" "<code>{}</code>\n" "I've gone and updated it with your new reason!".format( html.escape(old_reason) ), parse_mode=ParseMode.HTML, ) else: message.reply_text( "This user is already gbanned, but had no reason set; I've gone and updated it!" ) return message.reply_text( f"<b>Beginning of Global Ban for</b> {mention_html(user_chat.id, user_chat.first_name)}" f"\n<b>With ID</b>: <code>{user_chat.id}</code>" f"\n<b>Reason</b>: <code>{reason or 'No reason given'}</code>", parse_mode=ParseMode.HTML, ) banner = update.effective_user bannerid = banner.id bannername = banner.first_name reason = f"{reason} // GBanned by {bannername} banner id: {bannerid}" context.bot.sendMessage( MESSAGE_DUMP, "<b>New Global Ban</b>" "\n#GBAN" "\n<b>Status:</b> <code>Enforcing</code>" "\n<b>Sudo Admin:</b> {}" "\n<b>User:</b> {}" "\n<b>ID:</b> <code>{}</code>" "\n<b>Reason:</b> {}".format( mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason or "No reason given", ), parse_mode=ParseMode.HTML, ) try: context.bot.kick_chat_member(chat.id, user_chat.id) except BadRequest as excp: if excp.message in GBAN_ERRORS: pass sql.gban_user(user_id, user_chat.username or user_chat.first_name, reason)
def __init__(self, args): self.args = args self.display = Display("info_%s.log" % escape(args.bookid)) self.display.intro() self.cookies = {} self.jwt = {} if not args.cred: if not os.path.isfile(COOKIES_FILE): self.display.exit("Login: unable to find cookies file.\n" " Please use the --cred option to perform the login.") self.cookies = json.load(open(COOKIES_FILE)) else: self.display.info("Logging into Safari Books Online...", state=True) self.do_login(*args.cred) if not args.no_cookies: json.dump(self.cookies, open(COOKIES_FILE, "w")) self.book_id = args.bookid self.api_url = self.API_TEMPLATE.format(self.book_id) self.display.info("Retrieving book info...") self.book_info = self.get_book_info() self.display.book_info(self.book_info) self.display.info("Retrieving book chapters...") self.book_chapters = self.get_book_chapters() self.chapters_queue = self.book_chapters[:] if len(self.book_chapters) > sys.getrecursionlimit(): sys.setrecursionlimit(len(self.book_chapters)) self.book_title = self.book_info["title"] self.base_url = self.book_info["web_url"] self.clean_book_title = "".join(self.escape_dirname(self.book_title).split(",")[:2]) \ + " ({0})".format(self.book_id) books_dir = os.path.join(PATH, "Books") if not os.path.isdir(books_dir): os.mkdir(books_dir) self.BOOK_PATH = os.path.join(books_dir, self.clean_book_title) self.css_path = "" self.images_path = "" self.create_dirs() self.display.info("Output directory:\n %s" % self.BOOK_PATH) self.chapter_title = "" self.filename = "" self.css = [] self.images = [] self.display.info("Downloading book contents... (%s chapters)" % len(self.book_chapters), state=True) self.BASE_HTML = self.BASE_01_HTML + (self.KINDLE_HTML if not args.no_kindle else "") + self.BASE_02_HTML self.cover = False self.get() if not self.cover: self.cover = self.get_default_cover() cover_html = self.parse_html( html.fromstring("<div id=\"sbo-rt-content\"><img src=\"Images/{0}\"></div>".format(self.cover)), True ) self.book_chapters = [{ "filename": "default_cover.xhtml", "title": "Cover" }] + self.book_chapters self.filename = self.book_chapters[0]["filename"] self.save_page_html(cover_html) self.css_done_queue = Queue(0) if "win" not in sys.platform else WinQueue() self.display.info("Downloading book CSSs... (%s files)" % len(self.css), state=True) self.collect_css() self.images_done_queue = Queue(0) if "win" not in sys.platform else WinQueue() self.display.info("Downloading book images... (%s files)" % len(self.images), state=True) self.collect_images() self.display.info("Creating EPUB file...", state=True) self.create_epub() if not args.no_cookies: json.dump(self.cookies, open(COOKIES_FILE, "w")) self.display.done(os.path.join(self.BOOK_PATH, self.book_id + ".epub")) self.display.unregister() if not self.display.in_error and not args.log: os.remove(self.display.log_file) sys.exit(0)
int(result.group(5)), int(result.group(6)), tzinfo=timezone(timedelta(hours=9))) if result.group(7) == '自分': type_s = '2' else: type_s = '1' if result.group(8) == 'スタンプ': mmss.append( f'{time.isoformat()} {str(time.timestamp()).split(".")[0]}000 {type_s}' ) else: body = html.escape(result.group(8)) xmls.append( ET.Element( 'sms', { 'protocol': '0', 'address': phone_to, 'date': str(time.timestamp()).split('.')[0] + '000', 'type': type_s, 'subject': 'null', 'body': body,
def render_html_span(token): return html.escape(token.content)
def generate(self,article,html,**kwargs): generate_title = kwargs.get('generate_title',self.generate_title) generate_info = kwargs.get('generate_info',self.generate_info) resource = kwargs.get('resource') properties = article.generate_properties(resource=resource) for name in properties.keys(): value = properties[name] if name=='content': continue if name=='articleBody': continue if type(value)==str: if name=='resource': properties[name] = escape(value,quote=True) else: properties[name] = escape(value,quote=False) properties['keywords'] = ','.join(properties.get('keywords',[])) ld_properties = properties.copy() for name in ['title','description','keywords']: ld_properties[name] = quote_escape(ld_properties[name]) html.write("""<article xmlns="http://www.w3.org/1999/xhtml" vocab="http://schema.org/" typeof="BlogPosting" resource="{resource}"> <script type="application/ld+json"> {{ "@context" : "http://schema.org/", "@id" : "{id}", "@type" : "BlogPosting", "genre" : "{genre}", "headline" : "{title}", "description" : "{description}", "datePublished" : "{published}", "dateModified" : "{updated}", "keywords" : "{keywords}" """.format(**ld_properties)) if 'author' in properties: html.write(',\n"author" : [ ') authors = properties.get('author',[]) for index,author in enumerate(authors if type(authors)==list else [authors]): if (index>0): html.write(', ') html.write('{{ "@type" : "Person", "name" : "{}" }}'.format(author)) html.write(']') if 'publisher' in properties: publisher = properties['publisher'] html.write(',\n"publisher" : {') sep = ' ' for name in publisher.keys(): value = publisher[name] html.write(sep+'"{name}" : "{value}"'.format(name=name,value=value)) sep = ', ' html.write('}') html.write(""" } </script> """) if generate_title and not article.has_title: html.write("<h1 property='headline'>{}</h1>\n".format(properties['title'])) if generate_info: properties['publishedDisplay'] = ' '.join(properties['published'].split('T')) html.write('<section class="info">\n') html.write(''' <div class="metadata"> <p> <a href="{id}" title="link to this entry">🔗</a> Published on <span property="datePublished" content="{published}">{publishedDisplay}</span> <span property="dateModified" content="{updated}"></span> </p> <p property="keywords">{keywords}</p> <p property="description">{description}</p> </div> '''.format(**properties)) html.write('</p>\n') if 'author' in properties: authors = properties.get('author',[]) for index,author in enumerate(authors if type(authors)==list else [authors]): html.write('<p property="author" typeof="Person"><span property="name">{name}</span></p>\n'.format(name=author)) if 'publisher' in properties: publisher = properties['publisher'] for name in publisher.keys(): value = publisher[name] html.write('<p property="publisher" typeof="Organization"><span property="name">{name}</span></p>\n'.format(name=value)) html.write('</section>\n') if 'content' in properties: format = properties.get('format',Article.TEXT_MARKDOWN) self.transform_content(properties['content'],format,Article.TEXT_HTML,html) html.write('</article>\n')
def setDebugInfo(self, msg): if self.showDebug: self.txtLog.append('<span style="color:blue">{}</span>'.format(html.escape(msg, quote=False)))
def warn( user: User, chat: Chat, reason: str, message: Message, warner: User = None ) -> str: bot = dispatcher.bot if is_user_admin(chat, user.id): message.reply_text("Damn admins, can't even be warned!") return "" if not user.id or int(user.id) == 777000 or int(user.id) == 1087968824: message.reply_text("This is the Telegram Service Bot or the Group Anonymous Bot. Kinda pointless to warn it, don't you think?") return "" if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # kick chat.unban_member(user.id) reply = "That's {} warnings, {} has been kicked!".format( limit, mention_html(user.id, user.first_name) ) else: # ban chat.kick_member(user.id) reply = "That's{} warnings, {} has been banned!".format( limit, mention_html(user.id, user.first_name) ) for warn_reason in reasons: reply += "\n - {}".format(html.escape(warn_reason)) keyboard = None log_reason = ( "<b>{}:</b>" "\n#WARN_BAN" "\n<b>Admin:</b> {}" "\n<b>User:</b> {} (<code>{}</code>)" "\n<b>Reason:</b> {}" "\n<b>Counts:</b> <code>{}/{}</code>".format( html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit, ) ) else: keyboard = [[ InlineKeyboardButton("Remove warn", callback_data="rm_warn({})".format(user.id)) ]] rules = rules_sql.get_rules(chat.id) if rules: keyboard[0].append( InlineKeyboardButton("Rules", url="t.me/{}?start={}".format( bot.username, chat.id))) reply = "User {} has {}/{} warnings... watch out!".format( mention_html(user.id, user.first_name), num_warns, limit ) if reason: reply += "\nReason for last warn:\n{}".format(html.escape(reason)) log_reason = ( "<b>{}:</b>" "\n#WARN" "\n<b>Admin:</b> {}" "\n<b>User:</b> {} (<code>{}</code>)" "\n<b>Reason:</b> {}" "\n<b>Counts:</b> <code>{}/{}</code>".format( html.escape(chat.title), warner_tag, mention_html(user.id, user.first_name), user.id, reason, num_warns, limit, ) ) try: message.reply_text(reply, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text( reply, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML, quote=False ) else: raise return log_reason
def setCommand(self, cmd): if self.showDebug: self.txtLog.append('<code>{}<code>'.format(html.escape(cmd, quote=False)))
def setConsoleInfo(self, msg): if self.showDebug: self.txtLog.append('<code><span style="color:darkgray">{}</span></code>'.format(html.escape(msg, quote=False)))