如何防止机器人发送垃圾邮件? | Twitch.py​​ |不和谐.py

如何解决如何防止机器人发送垃圾邮件? | Twitch.py​​ |不和谐.py

我是 Python 新手,正在制作 Discord 机器人。所以在这里我有 twitch 通知功能,但是当有人是 live bot 时才开始发送垃圾邮件,我想是因为 idk 如何从嵌入中获取 content。请帮我。代码:

import os
import json
import discord
import requests
from discord.ext import tasks,commands
from discord.utils import get

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$',intents=intents)

TOKEN = os.getenv('token')

# Authentication with Twitch API.
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
body = {
    'client_id': client_id,'client_secret': client_secret,"grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token',body)
keys = r.json()
headers = {
    'Client-ID': client_id,'Authorization': 'Bearer ' + keys['access_token']
}

'''user_info = twitch.get_users(logins=['turb4ik'])
user_id = user_info['data'][0]['id']
print(user_info)'''

# Returns true if online,false if not.
def checkuser(streamer_name):
    stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name,headers=headers)
    stream_data = stream.json()

    if len(stream_data['data']) == 1:
        return True,stream_data
    else:
        return False,stream_data


# Executes when bot is started
@bot.event
async def on_ready():
    # Defines a loop that will run every 10 seconds (checks for live users every 10 seconds).
    @tasks.loop(seconds=10)
    async def live_notifs_loop():
        # username = stream_data['data'][0]['user_name']
        # stream_title = stream_data['data'][0]['title']
        # game_being_played = stream_data['data'][0]['game_name']

        # Opens and reads the json file
        with open('streamers.json','r') as file:
            streamers = json.loads(file.read())
        # Makes sure the json isn't empty before continuing.
        if streamers is not None:
            # Gets the guild,'twitch streams' channel,and streaming role.
            guild = bot.get_guild(690995360411156531)
            channel = bot.get_channel(798127930295058442)
            role = get(guild.roles,id=835581408272580649)
            # Loops through the json and gets the key,value which in this case is the user_id and twitch_name of
            # every item in the json.
            for user_id,twitch_name in streamers.items():
                print("checking" + " " + str(twitch_name))
                # Takes the given twitch_name and checks it using the checkuser function to see if they're live.
                # Returns either true or false.
                status,stream_data = checkuser(twitch_name)
                # Gets the user using the collected user_id in the json
                user = bot.get_user(int(user_id))
                # Makes sure they're live
                if status is True:
                    # Checks to see if the live message has already been sent.
                    async for message in channel.history(limit=200):
                        print("yes")
                        twitch_embed = discord.Embed(
                                title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}",color=0xac1efb,url=f'\nhttps://www.twitch.tv/{twitch_name}'
                            )
                        twitch_embed.add_field(
                              name = '**Game**',value = stream_data['data'][0]['game_name'],inline = True
                            )
                        twitch_embed.add_field(
                              name = '**Viewers**',value = stream_data['data'][0]['viewer_count'],inline = True
                            )
                        twitch_embed.set_author(
                                name = str(twitch_name),icon_url = stream_data['data'][0]['thumbnail_url']
                                                            )
                        twitch_embed.set_image(url = f'https://www.twitch.tv/{twitch_name}')
                        print("yes2")
                        try:
                            embed_title = twitch_embed.title
                            embed_description = twitch_embed.description
                        except Exception as e:
                            break
                        print("yes3")

                        # If it has,break the loop (do nothing).
                        if embed_title == True:
                            break
                        # If it hasn't,assign them the streaming role and send the message.
                        else:
                            # Gets all the members in your guild.
                            async for member in guild.fetch_members(limit=None):
                                # If one of the id's of the members in your guild matches the one from the json and
                                # they're live,give them the streaming role.
                                if member.id == int(user_id):
                                    await member.add_roles(role)
                            # Sends the live notification to the 'twitch streams' channel then breaks the loop.
                            await channel.send(
                                content = f"Hey @everyone! {user.name} is now streaming on Twitch! Go check it out: https://www.twitch.tv/{twitch_name}",embed=twitch_embed)
                            print(f"{user} started streaming. Sending a notification.")
                            break
                # If they aren't live do this:
                else:
                    # Gets all the members in your guild.
                    async for member in guild.fetch_members(limit=None):
                        # If one of the id's of the members in your guild matches the one from the json and they're not
                        # live,remove the streaming role.
                        if member.id == int(user_id):
                            await member.remove_roles(role)
                    # Checks to see if the live notification was sent.
                    async for message in channel.history(limit=200):
                        try:
                            embed_title = message.embeds[0].title
                            embed_description = message.embeds[0].description
                        except Exception as e:
                            break
                        # If it was,delete it.
                        if user.mention in embed_title and "is now playing" in embed_title:
                            print(f"{user} stopped streaming. Removing the notification.")
                            await message.delete()
    # Start your loop.
    live_notifs_loop.start()


# Command to add Twitch usernames to the json.
@bot.command(name='addtwitch',help='Adds your Twitch to the live notifs.',pass_context=True)
async def add_twitch(ctx,twitch_name):
    # Opens and reads the json file.
    with open('streamers.json','r') as file:
        streamers = json.loads(file.read())

    # Gets the users id that called the command.
    user_id = ctx.author.id
    # Assigns their given twitch_name to their discord id and adds it to the streamers.json.
    streamers[user_id] = twitch_name

    # Adds the changes we made to the json file.
    with open('streamers.json','w') as file:
        file.write(json.dumps(streamers))
    # Tells the user it worked.
    await ctx.send(f"Added {twitch_name} for {ctx.author} to the notifications list.")


print('Server Running')
bot.run(TOKEN) 

解决方法

只是为了其他人的情况,他向我展示了不和谐的错误,所以我通过这个问题回答他!

伙计,我发现了错误。

代码中的第 106 行是:

await message.channel.send(msg)

现在这个 msg 变量发送所有细节,但我们只想要它的内容而不是其他任何东西。

因此将其更改为:

await message.channel.send(msg.content)

谢谢! :D

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res