Background tasks in Python, check for already sent data - python

I have a question for experts here. I am creating background tasks for my Discord bot and I got it working as I wanted but I would like to implement a feature that will allow me to ignore data that was already sent. I am using data that is requested via requests as it changes over time.
Here is part of my code and this works as intended but I can't figure out how to add a part to check sent messages and not repeat it. I set 1 minute for testing to see does it work and this will change later on.
Thanks in advance
import discord
import requests
import asyncio
import json
from datetime import datetime, timezone
import math
from discord.ext import commands, tasks
from discord.ext.commands import Bot
import discord.utils
from itertools import cycle
client = discord.Client()
status = (['Scraping VATSIM Data','Anyone online?','What can I show you?', 'Check our social media for updates!'])
#client.event
async def on_ready():
change_status.start()
auto_online.start()
# await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="VATSIM Data!"))
print('We have logged in as {0.user}'.format(client))
#tasks.loop(minutes=1)
async def auto_online():
# send request to vatsim data
t = requests.get('http://cluster.data.vatsim.net/vatsim-data.json').json()
xy = json.dumps(t)
s = json.loads(xy)
channel1 = client.get_channel(692681048798265347)
# Bookins Data Display
utc = datetime.now(timezone.utc)
# Command for displaying ATC online
online_exists = False
for item in s['clients']:
if item['callsign'] in atc:
online_exists = True
embed = discord.Embed(colour = discord.Colour.purple())
embed.set_author(name='VATAdria Online ATC')
embed.add_field(name='Controller',value=item['realname'],inline=False)
embed.add_field(name='Position', value=item['callsign'], inline=False)
embed.add_field(name='Frequency', value=item['frequency'], inline=False)
await channel1.send( embed=embed)```

After doing some research I found out how to do this via MySQL. So no answers needed for this anymore.

Related

Discord bot (python) edit own message itself every minute

import os
import discord
import requests
import time
import datetime
class MyClient(discord.Client):
async def on_ready(self):
await client.change_presence(activity=discord.Activity(type=0, name='HIDDENSTATUS'))
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
msglower = message.content.lower()
channelStatusSV = client.get_channel(HIDDENCHANNELID)
if msglower == '!refresh':
standard = formated_info('HIDDENIP', '36963', 'ok')
messageStandard = await channelStatusSV.fetch_message(HIDDENMESSAGEID)
await messageStandard.edit(content=standard)
client = MyClient()
client.run('HIDDENTOKEN')
This is the full script (with some hidden info like IP, URL, etc).
It fetches my game server info into an embedded bot message. Currently, it fetches info on demand.
How can I change it to automatically fetch every minute?
Assuming that you're using discord.py; you can use tasks! Have it loop on the interval you want, query the server, and update the message.

Discord.py Timed message is not executing

So, I have created a command that executes a reoccurring message. I have it set to 10 seconds in the code for testing purposes, but I will have the message loop every 4 hours. I don't get any errors when running the code, but the command is not actually executing. The message never sends and I am confused as to why and can't seem to figure it out.
import discord
import discord.utils
import asyncio
import http.client
import aiohttp
import EZPaginator
import platform
import yaml
import os
from yaml import load, dump
from discord.ext import commands
from discord.ext import tasks
intents = discord.Intents.default()
client = commands.Bot(command_prefix = '$', intents=intents)
client.remove_command('help')
#client.event
async def on_ready():
print('ZOF BOT IS ONLINE!')
# Reoccuring Message Reminder
#tasks.loop(seconds=10)
async def send_message(ctx):
channel = discord.utils.get(ctx.guild.channels, name='reminders')
remind = discord.Embed(title='**:rotating_light:ATTENTION ZOF:', description='Do not forget to donate to Fortress, Alliance tech, and Ruins!', color=0xFFFFFF)
print('Reoccurring Message Sent.')
await channel.send(embed=remind) ```
You need to start you task function for example in on_ready event:
#client.event
async def on_ready():
if not send_message.is_running():
send_message.start()

Im trying to make a discord bot that sends a message reminding people that our secret santa is in 1 week but its isnt working

I've tried what I remembered but I'm still fairly new to discord.py so I can't spot what the problem is.
import discord
import os
import asyncio, datetime
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
asyncio.datetime.datetime((2021, 12, 10, 20, 41)
channel = (894709862091591724)
channel.message.send('#everyone the secret santa is in 1 week!'))
client = MyClient()
keep_alive()
client.run(os.getenv('TOKEN'))
If you want to send messages automatically (for example every day). You can use tasks.loop for it. It will run every 24 hours and send your message.
Also, if you make a simple bot and you don't have to use classes it's much easier to create a client with client = commands.Bot() instead of making a class. You also have to use client.get_channel(id) or await client.fetch_channel(id) to use channel.
# imports you need
import discord, asyncio, datetime
from discord.ext import commands, tasks
from keep_alive import keep_alive
client = commands.Bot(command_prefix="!") # creating client
#tasks.loop(hours=24) # you can change it to minutes or seconds too
async def secret_santa():
santa = datetime.date(2021, 12, 6) # your date (year, month, day)
today = datetime.date.today() # gets today's date
delta = (santa - today).days # calculates number of days to "santa" (I used ".days" to get only number of days)
channel = await client.fetch_channel(894709862091591724)
await channel.send(f'#everyone the secret santa is in {delta} days')
secret_santa.start() # starting task
keep_alive()
client.run(os.getenv('TOKEN'))

Can't server mute someone using discord.py

Basically whenever I run this code it gives me an error, I am trying to make the code server mute one of my friends every 20 seconds for 5 seconds, it says there is something wrong with the line where the user is being defined.
import discord
from discord.ext import commands
from discord.ext import commands, tasks
import random
import datetime
from datetime import date
import calendar
import time
import asyncio
from discord.ext.tasks import loop
client = commands.Bot(command_prefix='.')
#tasks.loop(seconds=20)
async def mute_person():
user = await discord.Guild.fetch_member("670549896247509002", "670549896247509002") # Get the Member Object
await user.edit(mute=True) # Mute
await asyncio.sleep(20) # Waits for 20 seconds then unmute.
await user.edit(mute=False) # Unmute
#client.event
async def on_ready():
print("I am ready")
mute_person.start()
client.run("Token")
You are not using the right function discord.Guild doesn't exist as you are using it. the main use must be await guild.fetch_member(member_id) and then guild means the guild object which has a specific ID as well. So you need to get the guild first.

Bot not changing status In discord.py I got no errors

I am not able to change the status. I want to develop my own bot and have to add more features too
# Importing Modules
import discord
import asyncio
import random
import DateTime
from discord.ext import commands
from urllib import parse, request
import re
import time
# Importants
bot = commands.Bot(command_prefix='*', description="This is a Helper Bot")
client = discord.Client()
# ***ADDING FEATURES***
# Getting Online And Changing status
async def my_background_task():
await client.wait_until_ready()
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="With Your Life"))
time.sleep(5)
# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="Kartik Jain", url="https://youtube.com/c/KartikJainChannel"))
time.sleep(5)
# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="To *help"))
time.sleep(5)
# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=" Your Nonsense"))
time.sleep(5)
# While Loop To loop changing statuses
while not bot.is_closed():
bot.bg_task = bot.loop.create_task(my_background_task())
# Making the bot online
client.run('My_ID')
You have to change the bot with client and you have to change this my_background_task() to this: on_ready().
Just look at this code:
import discord
import asyncio
import random
import DateTime
from discord.ext import commands
from urllib import parse, request
import re
import time
# Importants
bot = commands.Bot(command_prefix='*', description="This is a Helper Bot")
client = discord.Client()
# ***ADDING FEATURES***
# Getting Online And Changing status
#client.event
async def on_ready():
await client.change_presence(activity=discord.Streaming(name="My live",url="http://www.twitch.tv/G4merStop"))
time.sleep(5)
await client.change_presence(activity=discord.Streaming(name="Your live",url="http://www.twitch.tv/G4merStop"))
time.sleep(5)
# ^^^^ here you can see what you can do in the docs ^^^^
# Making the bot online
client.run('My_ID')```
First of all, you're actually creating 2 different instances of the client, client using discord.Client and bot using commands.Bot. You're using bot to change the presence, and in the end, you're running the client instance, which makes part done using bot totally useless.
You don't need to use discord.Client, because commands.Bot has all the methods and attributes of discord.Client.
Next, you should change time.sleep() to await asyncio.sleep() because it's blocking your code and also put the bot.loop.create_task() method inside on_ready event

Categories