Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from bottle import route, run # server to receive data
- import discord, asyncio
- from discord.ext import commands
- from queue import Queue # for safe communication between threads
- import threading
- import logging
- logging.basicConfig(level=logging.DEBUG)
- '''
- logger = logging.getLogger('discord')
- logger.setLevel(logging.INFO)
- handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
- handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
- logger.addHandler(handler)
- '''
- # 2 lines below have to be changed if you'd like to use this code yourself:
- channel_id = '480410810397622274'
- discord_bot_token = 'NDgwNDA5NzQ1ODU'
- server_port = 7891
- q = Queue()
- @route('<mypath:path>')
- def server_callback(mypath):
- print("server_callback -",datetime.datetime.time(datetime.datetime.now()))
- q.put(mypath)
- return "OK"
- def server_thread():
- run(host='localhost', port=server_port, debug=True)
- def FilterMessage(msg): # function that intakes received request/message and returns what will be posted on discord
- msg = msg[1:] # get rid of "/"
- if msg.startswith("[CMSG]"):
- #return msg
- 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!!!")
- return "IN GAME INFO: Our turf is taken over :("
- elif msg.startswith("[CHAT]"):
- pass # do nothing with chat messages received from players
- return
- client = discord.Client()
- import datetime
- async def my_background_task():
- await client.wait_until_ready()
- channel = discord.Object(id=channel_id)
- while not client.is_closed:
- try:
- #print("my_background_task() - try -",datetime.datetime.time(datetime.datetime.now()))
- msg = FilterMessage(q.get(False))
- except:
- #print("my_background_task() - except -",datetime.datetime.time(datetime.datetime.now()))
- pass
- else:
- #print("my_background_task() - else -",datetime.datetime.time(datetime.datetime.now()))
- if msg:
- await client.send_message(channel, msg)
- finally:
- print("my_background_task() - finally -",datetime.datetime.time(datetime.datetime.now()))
- await asyncio.sleep(0.1)
- @client.event
- async def on_ready():
- print('Logged in as')
- print(client.user.name)
- print(client.user.id)
- print('------')
- # example of additional functionality (used for testing, to make sure that it's not being blocked)
- @client.event
- async def on_message(message):
- import random
- # we do not want the bot to reply to itself
- if message.author == client.user:
- return
- if message.content.startswith('$guess'):
- await client.send_message(message.channel, 'Guess a number between 1 to 10')
- def guess_check(m):
- return m.content.isdigit()
- guess = await client.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
- answer = random.randint(1, 10)
- if guess is None:
- fmt = 'Sorry, you took too long. It was {}.'
- await client.send_message(message.channel, fmt.format(answer))
- return
- if int(guess.content) == answer:
- await client.send_message(message.channel, 'You are right!')
- else:
- await client.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))
- if __name__ == "__main__":
- server_thread = threading.Thread(target=server_thread)
- server_thread.daemon = True
- server_thread.start()
- client.loop.create_task(my_background_task())
- client.run(discord_bot_token)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement