twitter.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Twitter (microblogging platform)"""
  4. from json import loads
  5. from urllib.parse import urlencode
  6. from datetime import datetime
  7. about = {
  8. "website": 'https://twitter.com',
  9. "wikidata_id": None,
  10. "official_api_documentation": 'https://developer.twitter.com/en/docs/twitter-api',
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'JSON',
  14. }
  15. categories = ['social media']
  16. url = "https://api.twitter.com"
  17. search_url = (
  18. "{url}/2/search/adaptive.json?{query}&tweet_mode=extended&query_source=typed_query&pc=1&spelling_corrections=1"
  19. )
  20. def request(query, params):
  21. params['url'] = search_url.format(url=url, query=urlencode({'q': query}))
  22. params['headers'] = {
  23. # This token is used in the Twitter web interface (twitter.com). Without this header, the API doesn't work.
  24. # The value of the token has never changed (or maybe once a long time ago).
  25. # https://github.com/zedeus/nitter/blob/5f31e86e0e8578377fa7d5aeb9631bbb2d35ef1e/src/consts.nim#L5
  26. 'Authorization': (
  27. "Bearer AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKb"
  28. "T3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw"
  29. )
  30. }
  31. return params
  32. def response(resp):
  33. results = []
  34. json_res = loads(resp.text)['globalObjects']
  35. for tweet in json_res['tweets'].values():
  36. text = tweet['full_text']
  37. display = tweet['display_text_range']
  38. img_src = tweet.get('extended_entities', {}).get('media', [{}])[0].get('media_url_https')
  39. if img_src:
  40. img_src += "?name=thumb"
  41. results.append(
  42. {
  43. 'url': 'https://twitter.com/i/web/status/' + tweet['id_str'],
  44. 'title': (text[:40] + '...') if len(text) > 40 else text,
  45. 'content': text[display[0] : display[1]],
  46. 'img_src': img_src,
  47. 'publishedDate': datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S %z %Y'),
  48. }
  49. )
  50. for user in json_res['users'].values():
  51. results.append(
  52. {
  53. 'title': user['name'],
  54. 'content': user['description'],
  55. 'url': 'https://twitter.com/' + user['screen_name'],
  56. 'img_src': user['profile_image_url_https'],
  57. }
  58. )
  59. return results