From 4394e163e1194d8108440a549223fefefa20c308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Forr=C3=B3?= Date: Wed, 23 Sep 2020 17:53:26 +0200 Subject: [PATCH] Format mentions and urls in tweets --- bot.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 5bffe7c..8cbd262 100644 --- a/bot.py +++ b/bot.py @@ -3,6 +3,7 @@ import asyncio import configparser import datetime +import html import json import logging import os @@ -93,12 +94,27 @@ class Bot(discord.Client): return tweepy.API(handler) def make_twitter_embed(self, tweet): + def format_description(tweet_url): + text = tweet.get('text') + replacements = [] + for mention in tweet.get('entities', {}).get('user_mentions', []): + indices = mention.get('indices') + if indices: + replacements.append((indices, '[{0}]({1}{2})'.format(text[slice(*indices)], + TWITTER_USER_URL, mention.get('id_str')))) + for url in tweet.get('entities', {}).get('urls', []): + indices = url.get('indices') + if indices: + replacements.append((indices, '[{0}]({1})'.format(url.get('display_url', + text[slice(*indices)]), url.get('expanded_url')))) + for indices, replacement in sorted(replacements, key=lambda x: x[0][0], reverse=True): + text = text[:indices[0]] + replacement + text[indices[1]:] + return '{0}\n[{1}]({1})'.format(html.unescape(text), tweet_url) tweet_url = '{0}{1}'.format(TWITTER_STATUS_URL, tweet.get('id_str')) author_url = '{0}{1}'.format(TWITTER_USER_URL, tweet.get('user', {}).get('id_str')) author_handle = '@{0}'.format(tweet.get('user', {}).get('screen_name')) - description = '{0}\n[{1}]({1})'.format(tweet.get('text'), tweet_url) embed = discord.Embed( - description=description, + description=format_description(tweet_url), url=tweet_url, color=TWITTER_COLOR )