Format mentions and urls in tweets

master
Nikola Forró 4 years ago
parent 6cbbd3898f
commit 4394e163e1

@ -3,6 +3,7 @@
import asyncio import asyncio
import configparser import configparser
import datetime import datetime
import html
import json import json
import logging import logging
import os import os
@ -93,12 +94,27 @@ class Bot(discord.Client):
return tweepy.API(handler) return tweepy.API(handler)
def make_twitter_embed(self, tweet): 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')) 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_url = '{0}{1}'.format(TWITTER_USER_URL, tweet.get('user', {}).get('id_str'))
author_handle = '@{0}'.format(tweet.get('user', {}).get('screen_name')) author_handle = '@{0}'.format(tweet.get('user', {}).get('screen_name'))
description = '{0}\n[{1}]({1})'.format(tweet.get('text'), tweet_url)
embed = discord.Embed( embed = discord.Embed(
description=description, description=format_description(tweet_url),
url=tweet_url, url=tweet_url,
color=TWITTER_COLOR color=TWITTER_COLOR
) )

Loading…
Cancel
Save