joytou commited on
Commit
9cf96c4
1 Parent(s): 70e844e

Upload 3 files

Browse files
Files changed (3) hide show
  1. discord_bot.py +88 -0
  2. pingpong.py +39 -0
  3. server.py +65 -0
discord_bot.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is based on the following example:
2
+ # https://discordpy.readthedocs.io/en/stable/quickstart.html#a-minimal-bot
3
+
4
+ import os
5
+
6
+ import discord
7
+
8
+ from discord.ext import commands
9
+
10
+ from threading import Thread
11
+
12
+ import json
13
+
14
+
15
+
16
+ intents = discord.Intents.default()
17
+ intents.messages = True
18
+ bot = commands.Bot(command_prefix='>', intents=intents)
19
+
20
+ @bot.command()
21
+ async def ping(ctx):
22
+ await ctx.send('pong')
23
+
24
+ @bot.event
25
+ async def on_ready():
26
+ print('We have logged in as {0.user}'.format(bot))
27
+
28
+
29
+ @bot.event
30
+ async def on_message(message):
31
+ if message.author == bot.user:
32
+ return
33
+
34
+ if message.content == 'ping':
35
+ await message.channel.send('pong')
36
+
37
+ if message.content.startswith('$hello'):
38
+ await message.channel.send('Hello!')
39
+
40
+ async def sendMessageToChannelHelper(data):
41
+ channel = await bot.fetch_channel(os.getenv("CHANNEL_ID"))
42
+ # 创建一个 embed 对象
43
+ mTitle = "Empty Title"
44
+ if "id" in data:
45
+ mTitle = data["id"]
46
+ if "log_tag" in data:
47
+ mTitle = data["log_tag"]
48
+ mDescription = "Empty Description"
49
+ if "model" in data:
50
+ mDescription = data["model"]
51
+ if "log_message" in data:
52
+ mDescription = data["log_message"]
53
+ mColor = 0x00ff00
54
+ if ("log_tag" in data or "log_message" in data) and (data["log_level"] == "assert" or data["log_level"] == "error"):
55
+ mColor = 0xff0000
56
+ embed = discord.Embed(title=mTitle, description=mDescription, color=mColor)
57
+ # 将 fields 数据加入 embed
58
+ for field in data:
59
+ if field == "img":
60
+ embed.set_image(url=data[field])
61
+ else:
62
+ embed.add_field(name=field, value=data[field], inline=True)
63
+ # 发送 embed 消息
64
+ await channel.send(embed=embed)
65
+
66
+ def sendMessageToChannel(data):
67
+ bot.loop.create_task(sendMessageToChannelHelper(data))
68
+
69
+ def run():
70
+ try:
71
+ token = os.getenv("TOKEN") or ""
72
+ if token == "":
73
+ raise Exception("Please add your token to the Secrets pane.")
74
+ bot.run(token)
75
+ except discord.HTTPException as e:
76
+ if e.status == 429:
77
+ print(
78
+ "The Discord servers denied the connection for making too many requests"
79
+ )
80
+ print(
81
+ "Get help from https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests"
82
+ )
83
+ else:
84
+ raise e
85
+
86
+ def discord_bot():
87
+ print("Running discord_bot")
88
+ run()
pingpong.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ from threading import Timer
4
+
5
+ import time
6
+
7
+ import requests
8
+
9
+ import os
10
+
11
+ # 每隔4分钟发送ping
12
+
13
+ def sendPingTask():
14
+ Timer(240, sendPing, ()).start()
15
+
16
+ def sendPing():
17
+ print("sendPing")
18
+ url = os.getenv("WEBHOOK_URL")
19
+ headers = {
20
+ "Content-Type": "application/json"
21
+ }
22
+ payload = {
23
+ "content": "ping"
24
+ }
25
+ response = requests.post(url, json=payload, headers=headers)
26
+ if response.status_code == 200 or response.status_code == 204:
27
+ print("Message ping sent successfully")
28
+ sendPingTask()
29
+ else:
30
+ print(f"Failed to send message ping: {response.status_code}")
31
+
32
+ def run():
33
+ sendPingTask()
34
+ sendPing()
35
+
36
+ def pingpong():
37
+ print("Running pingpong")
38
+ run()
39
+
server.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # server.py
2
+ # where your python app starts
3
+
4
+ # init project
5
+ from flask import Flask, jsonify, render_template, request
6
+ #from typing_extensions import Literal
7
+ #from quart import Quart, jsonify, render_template, request
8
+ from discord_bot import discord_bot, sendMessageToChannel
9
+ from pingpong import pingpong
10
+ from threading import Thread
11
+ application = Flask(__name__)
12
+ #application.config['TIMEOUT'] = 1000
13
+
14
+
15
+ # I've started you off with Flask,
16
+ # but feel free to use whatever libs or frameworks you'd like through `.requirements.txt`.
17
+
18
+ # unlike express, static files are automatic: http://flask.pocoo.org/docs/0.12/quickstart/#static-files
19
+
20
+ # http://flask.pocoo.org/docs/0.12/quickstart/#routing
21
+ # http://flask.pocoo.org/docs/0.12/quickstart/#rendering-templates
22
+ @application.route('/')
23
+ def hello():
24
+ return render_template('index.html')
25
+
26
+ # Simple in-memory store
27
+ dreams = [
28
+ 'Find and count some sheep',
29
+ 'Climb a really tall mountain',
30
+ 'Wash the dishes',
31
+ ]
32
+
33
+ @application.route('/status')
34
+ def status():
35
+ return "Hello. I am alive!"
36
+
37
+ @application.route('/webhook', methods=['POST'])
38
+ def webhook():
39
+ data = request.json
40
+ message = data.get('message', 'No message provided')
41
+ if 'id' in data or 'log_message' in data:
42
+ sendMessageToChannel(data)
43
+ return data
44
+ return jsonify({'status': 'Message sent to Discord'})
45
+
46
+ @application.route('/dreams', methods=['GET'])
47
+ def get_dreams():
48
+ return jsonify(dreams)
49
+
50
+ # could also use the POST body instead of query string: http://flask.pocoo.org/docs/0.12/quickstart/#the-request-object
51
+ @application.route('/dreams', methods=['POST'])
52
+ def add_dream():
53
+ dreams.append(request.args.get('dream'))
54
+ return ''
55
+
56
+ # listen for requests
57
+ def run():
58
+ if __name__ == "__main__":
59
+ from os import environ
60
+ application.run(host='0.0.0.0', port=int(environ['PORT']))
61
+
62
+ t = Thread(target=run)
63
+ t.start()
64
+ pingpong()
65
+ discord_bot()