I wanted to make a bot which will send a fact every day (I took some code from there). But there is a problem. My bot sends same message every day. Why it doesn't work properly?
import os
import time
import discord
import json
from discord.ext import commands
from datetime import datetime, time, timedelta
import bilgiler_sözlüğü
from server import server
server()
TOKEN = os.environ['bot_token']
client = discord.Client()
sira = 1
def zaman():
print("Zaman komutu çalıştırıldı.")
while True:
current_time = datetime.now().strftime("%H:%M")
if current_time == "05:45":
global sayac
print("Zaman eşleştirildi.")
break
zaman()
#client.event
async def on_ready():
global sira
print("{0.user}".format(client), "çalıştırıldı.")
channel = client.get_channel(1001947725635530805)
try:
await channel.send(bilgiler_sözlüğü.sözlük[sira])
sira += 1
except KeyError:
await channel.send("Bilgilerim bitti!")
client.run(TOKEN)
"sira" is the variable which pulls out my dictionary. It must increase day by day. What must I do?
My bot is working now. For wonderers, its code:
import os
import time
import discord
import json
from discord.ext import commands
from datetime import datetime, time, timedelta
import bilgiler_sözlüğü
from server import server
server()
TOKEN = os.environ['bot_token']
client = discord.Client()
bugün = datetime.now().strftime("%d:%m")
#client.event
async def on_ready():
print("{0.user}".format(client), "çalıştırıldı.")
channel = client.get_channel(1001947725635530805)
try:
await channel.send(bilgiler_sözlüğü.sözlük[bugün])
except KeyError:
await channel.send("Bilgilerim bitti!")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("/gbbilgi"):
await message.channel.send("**Günün Bilgisi**, her gün saat 00:00'da kanalınıza bir bilgi gönderen bir bottur.\n\n**Yapıcı:** Ajan Smith#4747")
client.run(TOKEN)
server.py:
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return '<h1>Günün Bilgisi</h1>'
def run():
app.run(host='0.0.0.0',port=8080)
def server():
t = Thread(target=run)
t.start()
#Source: https://gist.github.com/beaucarnes/51ec37412ab181a2e3fd320ee474b671
Related
currently iam creating a log embed .
and i want give a bot.listen event a name.
and use it as Embed(title=f'{the name}' so i can use the same embed i build for multiple listen events .
for example :
#bot.py
from http import client
import discord
import asyncio
from discord.ext import commands
import os
from dotenv import load_dotenv
from datetime import datetime, timedelta, date, time, timezone
import time
import loging
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$"), help_command=None)
timestamp = datetime.now()
timenow = str(timestamp.strftime(r"%x, %X"))
#bot.listen(name='complexity')#give the name i want show as tittle
async def on_message(message):
if any(x in message.content.lower() for x in ["complexity", "complex"]):
await message.add_reaction(r":complexity:945474998208958517")
await loging.meslog(bot, message)
bot.run(TOKEN)
#loging.py
from http import client
import discord
import asyncio
from discord.ext import commands
import os
from datetime import datetime, timedelta, date, time, timezone
import time
timestamp = datetime.now()
timenow = str(timestamp.strftime(r"%x, %X"))
async def meslog(bot, message):
username = (message.author)
usernameid = str(message.author.id)
messagein = str(message.content)
messageid = str(message.id)
if message.guild:
channel = str(message.channel.name)
channelid = str(message.channel.id)
channelping = str(message.channel.mention)
logingchan = await bot.fetch_channel(983811124929630239)
em = discord.Embed(title=f'{message.name}', description=f'{timenow}', color=0x00FF00)
#{message.name} would output the name of the listen event.
#in this case Complexity
em.set_thumbnail(url=username.avatar_url)
em.add_field(name="Channel:", value=f'{channelping} \n{channelid}', inline=True)
em.add_field(name="User:", value=f'{username}\n{usernameid}', inline=True)
em.add_field(name="Message:", value=f'{messagein}\n{messageid}', inline=False)
await logingchan.send(embed=em)
i know its worng and dont work , but is there any way to do waht i mean to do ?
what is the correct way pls teach me.
The listen decorator does not support custom names. It must be one of the actual events, like on_message.
You probably have it backwards:
#bot.listen(name='on_message')
async def complexity(message):
if any(x in message.content.lower() for x in ["complexity", "complex"]):
await message.add_reaction(r":complexity:945474998208958517")
await loging.meslog(bot, message, 'complexity')
If you want to include the listener that called this, simply pass that as an argument:
async def meslog(bot, message, logger_name: str):
# ...
em = discord.Embed(title=f'{logger_name}', description=f'{timenow}', color=0x00FF00)
# ...
If you want to be really fancy, you can get the caller function's name (requires 3.5+) from meslog, but I personally don't recommend this:
async def meslog(bot, message, logger_name: str):
# ...
em = discord.Embed(title=f'{inspect.stack()[1].function}', description=f'{timenow}', color=0x00FF00)
# this will return 'complexity' but you can name it whatever
# ...
I have these two files:
main.py
import os
import discord
from keep_alive import keep_alive
client = discord.Client()
my_secret = os.environ['Token']
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive()
client.run(my_secret)
keep_alive.py
from flask import Flask
from threading import Thread
#from main import SendMeMessage
app = Flask('')
#app.route('/')
def home():
#SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
And I would like to import SendMemessage. So when someone send get request on flask server, I wanna receive message from my discord bot. I'm stuck on error "circular import", when I implement commented code.
I would move the discord bot code out of main.py, so it no longer depends on an import of keep_alive.
bot.py:
import os
import discord
client = discord.Client()
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive.py:
from flask import Flask
from threading import Thread
from bot import SendMeMessage
app = Flask('')
#app.route('/')
def home():
SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
main.py:
import os
from keep_alive import keep_alive
from bot import client
my_secret = os.environ['Token']
keep_alive()
client.run(my_secret)
This way, bot.py has already been fully imported when keep_alive.py runs, so there is no longer a circular import.
The plan for this bot is to wake up --> retrieve data I need --> terminate itself.
I've tried using client.logout() and client.close(), but the program won't stop after it runs. Any advice?
import discord
import os
from discord.ext import tasks
from discord.ext import commands
discord_client = discord.Client()
#discord_client.event
async def on_ready():
for guild in discord_client.guilds:
if guild.name == GUILD:
break
print(
f'{discord_client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
# Send message when Bot wakes up
channel = discord_client.get_channel(ID)
await channel.send("*wakes up and starts working*")
retrieve_data.start()
await discord_client.logout()
#tasks.loop(count=1)
async def retrieve_data():
# do things here
discord_client.run(TOKEN)
You don't have your token defined, import load_dotenv and call it, you have undefined variables, also logout() is deprecated so use close() instead and it works.
import discord
import os
from discord.ext import tasks
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
discord_client = discord.Client()
#discord_client.event
async def on_ready():
# for guild in discord_client.guilds:
# if guild.name == GUILD:
# break
# print(
# f'{discord_client.user} is connected to the following guild:\n'
# f'{guild.name}(id: {guild.id})'
# )
# Send message when Bot wakes up
# channel = discord_client.get_channel(ID)
# await channel.send("*wakes up and starts working*")
await retrieve_data.start()
await discord_client.close()
#tasks.loop(count=1)
async def retrieve_data():
print("test")
discord_client.run(os.getenv("TOKEN"))
import discord
import os
intents = discord.Intents.default()
intents.members = True
#client.event
async def on_member_join(member):
if member.guild.name == 'Bot Test Server':
await client.get_channel(927272717227528262).send("https://tenor.com/view/welcome-to-hell-lucifer-morningstar-tom-ellis-lucifer-welcome-gif-18399120")
else:
return
Everything is set correctly and it should send the message, but nothing happens.
Why you didn't initialize client? and I fixed your code since it's not clear nor doesn't look like from dpy docs
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='', intents=discord.Intents.all())
#client.event
async def on_member_join(member):
if member.guild.name == 'Bot Test Server':
channel = client.get_channel(927272717227528262)
await channel.send("https://tenor.com/view/welcome-to-hell-lucifer-morningstar-tom-ellis-lucifer-welcome-gif-18399120")
else:
return
client.run('')
I run this, it connects however when running it will not return anything when it comes to commands. I've tried changing this to the context return method from on every message. Previously only one message would appear, now none with this method even though both commands are the same with slight differences. What is my error on this? Sorry this is literally my first attempt at a discord bot.
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
discClient = discord.Client()
bot = commands.Bot(command_prefix = "!")
#discClient.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
discClient.run(botToken)
You heading in the right direction commands.Bot have both event and command no need to use a client just for events.
You should either use discord.Client or commands.Bot not both in your case it is commands.Bot.
Also you are running the client only
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
bot.run(botToken)