__init__.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # location-guessing-game-telegram-bot - Telegram Bot Sending Random Wikimedia Commons Photos
  2. #
  3. # Copyright (C) 2021 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import argparse
  18. import json
  19. import logging
  20. import os
  21. import pathlib
  22. import random
  23. import typing
  24. import urllib.request
  25. import telegram.ext
  26. import telegram.update
  27. _LOGGER = logging.getLogger(__name__)
  28. class _Photo:
  29. def __init__(
  30. self, photo_url: str, description_url: str, latitude: float, longitude: float
  31. ) -> None:
  32. self.photo_url = photo_url
  33. self.description_url = description_url
  34. self.latitude = latitude
  35. self.longitude = longitude
  36. def __str__(self) -> str:
  37. return "photo " + self.description_url
  38. @classmethod
  39. def from_wikimap_export(cls, data: dict) -> "_Photo":
  40. if isinstance(data["coordinates"], list):
  41. coords = data["coordinates"][0]
  42. else:
  43. coords = data["coordinates"]["1"]
  44. assert len(data["imageinfo"]) == 1, data["imageinfo"]
  45. return cls(
  46. latitude=coords["lat"],
  47. longitude=coords["lon"],
  48. photo_url=data["imageinfo"][0]["url"],
  49. description_url=data["imageinfo"][0]["descriptionurl"],
  50. )
  51. def _photo_command(
  52. update: telegram.update.Update,
  53. context: telegram.ext.callbackcontext.CallbackContext,
  54. ):
  55. if "last_photo_message_id" in context.chat_data:
  56. update.effective_chat.send_message(
  57. text="Lösung: {}".format(context.chat_data["last_photo"].description_url),
  58. disable_web_page_preview=True,
  59. reply_to_message_id=context.chat_data["last_photo_message_id"],
  60. )
  61. # https://github.com/python-telegram-bot/python-telegram-bot/pull/2043
  62. update.effective_chat.send_location(
  63. latitude=context.chat_data["last_photo"].latitude,
  64. longitude=context.chat_data["last_photo"].longitude,
  65. disable_notification=True,
  66. )
  67. context.chat_data["last_photo_message_id"] = None
  68. update.effective_chat.send_message(
  69. text="Neues Photo wird ausgewählt und gesendet.", disable_notification=True
  70. )
  71. while True:
  72. photo = random.choice(context.bot_data["photos"])
  73. _LOGGER.info("sending %s", photo)
  74. try:
  75. with urllib.request.urlopen(photo.photo_url) as photo_response:
  76. photo_message = update.effective_chat.send_photo(
  77. photo=photo_response,
  78. caption="Wo wurde dieses Photo aufgenommen?",
  79. )
  80. except telegram.error.BadRequest:
  81. _LOGGER.warning("file size limit exceeded?", exc_info=True)
  82. except telegram.error.TimedOut:
  83. _LOGGER.warning("timeout", exc_info=True)
  84. else:
  85. break
  86. context.chat_data["last_photo"] = photo
  87. context.chat_data["last_photo_message_id"] = photo_message.message_id
  88. class _Persistence(telegram.ext.BasePersistence):
  89. """
  90. found no easier way to inject bot_data
  91. https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.basepersistence.html
  92. """
  93. def __init__(self, photos: typing.List[_Photo]) -> None:
  94. self._bot_data = {"photos": photos}
  95. super().__init__(
  96. store_bot_data=True, store_chat_data=False, store_user_data=False
  97. )
  98. def get_user_data(self) -> dict:
  99. return {} # pragma: no cover
  100. def get_chat_data(self) -> dict:
  101. return {} # pragma: no cover
  102. def get_bot_data(self) -> dict:
  103. return self._bot_data
  104. def get_conversations(self, name: str) -> dict:
  105. return {} # pragma: no cover
  106. def update_user_data(self, user_id: int, data: dict) -> None:
  107. pass # pragma: no cover
  108. def update_chat_data(self, chat_id: int, data: dict) -> None:
  109. pass # pragma: no cover
  110. def update_bot_data(self, data: dict) -> None:
  111. pass # pragma: no cover
  112. def update_conversation(
  113. self, name: str, key: tuple, new_state: typing.Optional[object]
  114. ) -> None:
  115. pass # pragma: no cover
  116. # https://git.hammerle.me/fphammerle/pyftpd-sink/src/5daf383bc238425cd37d011959a8eeffab0112c3/pyftpd-sink#L48
  117. class _EnvDefaultArgparser(argparse.ArgumentParser):
  118. def add_argument(self, *args, envvar=None, **kwargs):
  119. # pylint: disable=arguments-differ; using *args & **kwargs to catch all
  120. if envvar:
  121. envvar_value = os.environ.get(envvar, None)
  122. if envvar_value:
  123. kwargs["required"] = False
  124. kwargs["default"] = envvar_value
  125. super().add_argument(*args, **kwargs)
  126. def _run(telegram_token_path: pathlib.Path, wikimap_export_path: pathlib.Path) -> None:
  127. photos = [
  128. _Photo.from_wikimap_export(attrs)
  129. for attrs in json.loads(wikimap_export_path.read_text())
  130. ]
  131. updater = telegram.ext.Updater(
  132. token=telegram_token_path.read_text().rstrip(),
  133. use_context=True,
  134. persistence=_Persistence(photos=photos),
  135. )
  136. updater.dispatcher.add_handler(telegram.ext.CommandHandler("photo", _photo_command))
  137. updater.start_polling()
  138. def _main():
  139. argparser = _EnvDefaultArgparser()
  140. argparser.add_argument(
  141. "--telegram-token-path",
  142. type=pathlib.Path,
  143. required=True,
  144. envvar="TELEGRAM_TOKEN_PATH",
  145. help="default: env var TELEGRAM_TOKEN_PATH",
  146. )
  147. argparser.add_argument(
  148. "--wikimap-export-path",
  149. type=pathlib.Path,
  150. required=True,
  151. envvar="WIKIMAP_EXPORT_PATH",
  152. help="https://wikimap.toolforge.org/api.php?[...] json, "
  153. "default: env var WIKIMAP_EXPORT_PATH",
  154. )
  155. argparser.add_argument("--debug", action="store_true")
  156. args = argparser.parse_args()
  157. # https://github.com/fphammerle/python-cc1101/blob/26d8122661fc4587ecc7c73df55b92d05cf98fe8/cc1101/_cli.py#L51
  158. logging.basicConfig(
  159. level=logging.DEBUG if args.debug else logging.INFO,
  160. format="%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s"
  161. if args.debug
  162. else "%(message)s",
  163. datefmt="%Y-%m-%dT%H:%M:%S%z",
  164. )
  165. _LOGGER.debug("args=%r", args)
  166. _run(
  167. telegram_token_path=args.telegram_token_path,
  168. wikimap_export_path=args.wikimap_export_path,
  169. )