Без опису

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from matrix_client.client import MatrixClient
  2. import requests
  3. import json
  4. import discord
  5. import re
  6. from config import *
  7. matrix_client = MatrixClient(matrix_homeserver, token=matrix_token, user_id=matrix_user_id)
  8. discord_client = discord.Client()
  9. matrix_room = matrix_client.join_room(matrix_room_id)
  10. @discord_client.event
  11. async def on_message(message):
  12. if message.author.discriminator == "0000": return
  13. username = message.author.display_name[:1] + "\u200B" + message.author.display_name[1:]
  14. matrix_room.send_text("<{}> {}".format(username, message.clean_content))
  15. def send_webhook(username, avatar_url, content):
  16. data = {'username': username, 'content': content}
  17. if avatar_url: data['avatar_url'] = avatar_url
  18. headers = {'Content-type': 'application/json'}
  19. r = requests.post(webhook_url, data = json.dumps(data), headers=headers)
  20. def prepare_discord_content(content):
  21. content = content.replace("@everyone", "@\u200Beveryone")
  22. content = content.replace("@here", "@\u200Bhere")
  23. mentions = re.findall("(^|\s)(@(\w*))", content)
  24. guild = discord_client.get_channel(discord_channel).guild
  25. for mention in mentions:
  26. member = guild.get_member_named(mention[2])
  27. if not member: continue
  28. content = content.replace(mention[1], member.mention)
  29. return content
  30. def on_matrix_message(room, event):
  31. if event['type'] == "m.room.message":
  32. user = matrix_client.get_user(event['sender'])
  33. if event['content']['msgtype'] == "m.text" and not user.user_id == matrix_user_id:
  34. username = "[Matrix] {}".format(user.get_display_name())
  35. avatar = user.get_avatar_url()
  36. content = prepare_discord_content(event['content']['body'])
  37. send_webhook(username, avatar, content)
  38. matrix_room.add_listener(on_matrix_message)
  39. matrix_client.start_listener_thread()
  40. discord_client.run(discord_token)