Advertisement
michalmonday

testing_samp_discord

Aug 23rd, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.84 KB | None | 0 0
  1. from bottle import route, run # server to receive data
  2.  
  3. import discord, asyncio
  4. from discord.ext import commands
  5.  
  6. from queue import Queue # for safe communication between threads
  7. import threading
  8.  
  9.  
  10. import logging
  11. logging.basicConfig(level=logging.DEBUG)
  12.  
  13. '''
  14. logger = logging.getLogger('discord')
  15. logger.setLevel(logging.INFO)
  16. handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
  17. handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
  18. logger.addHandler(handler)
  19. '''
  20.  
  21. # 2 lines below have to be changed if you'd like to use this code yourself:
  22. channel_id = '480410810397622274'
  23. discord_bot_token = 'NDgwNDA5NzQ1ODU'
  24.  
  25. server_port = 7891
  26.  
  27. q = Queue()
  28.  
  29. @route('<mypath:path>')
  30. def server_callback(mypath):
  31.     print("server_callback -",datetime.datetime.time(datetime.datetime.now()))
  32.     q.put(mypath)
  33.     return "OK"
  34.  
  35. def server_thread():
  36.     run(host='localhost', port=server_port, debug=True)
  37.  
  38.  
  39. def FilterMessage(msg): # function that intakes received request/message and returns what will be posted on discord
  40.     msg = msg[1:] # get rid of "/"
  41.     if msg.startswith("[CMSG]"):
  42.         #return msg
  43.         if "Your turf is being taken over!!!" in msg[6:]: # if that phrase is within message (safe in cases where space is added after/before), there could be check if the message is equal to that phrase though (using if msg[6:] == "Your turf is being taken over!!!")
  44.             return "IN GAME INFO: Our turf is taken over :("
  45.     elif msg.startswith("[CHAT]"):
  46.         pass # do nothing with chat messages received from players
  47.     return        
  48.  
  49. client = discord.Client()
  50.  
  51. import datetime
  52.  
  53. async def my_background_task():
  54.     await client.wait_until_ready()
  55.     channel = discord.Object(id=channel_id)
  56.     while not client.is_closed:
  57.         try:
  58.             #print("my_background_task() - try -",datetime.datetime.time(datetime.datetime.now()))
  59.             msg = FilterMessage(q.get(False))
  60.         except:
  61.             #print("my_background_task() - except -",datetime.datetime.time(datetime.datetime.now()))
  62.             pass
  63.         else:
  64.             #print("my_background_task() - else -",datetime.datetime.time(datetime.datetime.now()))
  65.             if msg:
  66.                 await client.send_message(channel, msg)
  67.         finally:
  68.             print("my_background_task() - finally -",datetime.datetime.time(datetime.datetime.now()))
  69.             await asyncio.sleep(0.1)
  70.        
  71. @client.event
  72. async def on_ready():
  73.     print('Logged in as')
  74.     print(client.user.name)
  75.     print(client.user.id)
  76.     print('------')
  77.  
  78.  
  79. # example of additional functionality (used for testing, to make sure that it's not being blocked)
  80. @client.event
  81. async def on_message(message):
  82.     import random
  83.     # we do not want the bot to reply to itself
  84.     if message.author == client.user:
  85.         return
  86.  
  87.     if message.content.startswith('$guess'):
  88.         await client.send_message(message.channel, 'Guess a number between 1 to 10')
  89.  
  90.         def guess_check(m):
  91.             return m.content.isdigit()
  92.  
  93.         guess = await client.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
  94.         answer = random.randint(1, 10)
  95.         if guess is None:
  96.             fmt = 'Sorry, you took too long. It was {}.'
  97.             await client.send_message(message.channel, fmt.format(answer))
  98.             return
  99.         if int(guess.content) == answer:
  100.             await client.send_message(message.channel, 'You are right!')
  101.         else:
  102.             await client.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))
  103.  
  104.  
  105. if __name__ == "__main__":
  106.     server_thread = threading.Thread(target=server_thread)
  107.     server_thread.daemon = True
  108.     server_thread.start()
  109.  
  110.     client.loop.create_task(my_background_task())
  111.     client.run(discord_bot_token)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement