bot_news.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from slixmpp import ClientXMPP
  2. from newsapi import NewsApiClient
  3. import time
  4. class Bot(ClientXMPP):
  5. def __init__(self, jid, password):
  6. ClientXMPP.__init__(self, jid, password)
  7. self.add_event_handler("session_start", self.start)
  8. self.add_event_handler("message", self.message)
  9. self.news_api = NewsApiClient(api_key='ваш_api_ключ')
  10. def start(self, event):
  11. self.send_presence()
  12. self.get_roster()
  13. def message(self, msg):
  14. if msg['type'] in ('chat', 'normal'):
  15. message_text = msg['body']
  16. if "news" in message_text.lower():
  17. news_titles = self.get_news_titles()
  18. for title in news_titles:
  19. msg.reply(title).send()
  20. time.sleep(1)
  21. def get_news_titles(self):
  22. headlines = self.news_api.get_top_headlines(language='ru', country='ru', page_size=5)
  23. return [article['title'] for article in headlines['articles']]
  24. if __name__ == '__main__':
  25. xmpp = Bot("ваш_jabber_id", "ваш_пароль")
  26. xmpp.connect()
  27. xmpp.process()