Chat Bot don't polling - python

I,m just study codding, and try make chat-bot. But it's don' work, please help me.
I'ts my code:
import time
import logging
from aiogram import Bot, Dispatcher, types, executor
logging.basicConfig(level=logging.INFO)
TOKEN = '6292675773:AAGBBeUms_4NILy6h26TH4rGLyml7h3bHWg'
MSG = 'Hello, are you coddind today?'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot=bot)
#dp.message_handler(Commands=['start'])
async def start_handler(message: types.Message):
user_id = message.from_user.id
user_name = message.from_user.first_name
user_full_name = message.from_user.first_name
logging.info(f'{user_id} {user_full_name} {time.asctime()}')
await message.reply(f"Hello, {user_full_name}!")
for i in range(10):
time.sleep(2)
await bot.send_message(user_id, MSG.format(user_name))
if __name__ == '__main__':
executor.start_polling(dp)
and it's Error:
(venv) PS C:\Users\roman\PycharmProjects\pythonProject> python main.py
Traceback (most recent call last):
File "C:\Users\roman\PycharmProjects\pythonProject\main.py", line 14, in
#dp.message_handler(Commands = ['start'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\roman\PycharmProjects\pythonProject\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 560, in decorator
self.register_message_handler(callback, *custom_filters,
File "C:\Users\roman\PycharmProjects\pythonProject\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 479, in register_message_handler
filters_set = self.filters_factory.resolve(self.message_handlers,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\roman\PycharmProjects\pythonProject\venv\Lib\site-packages\aiogram\dispatcher\filters\factory.py", line 51, in resolve
filters_set = list(
^^^^^
File "C:\Users\roman\PycharmProjects\pythonProject\venv\Lib\site-packages\aiogram\dispatcher\filters\factory.py", line 77, in _resolve_registered
raise NameError("Invalid filter name(s): '" + "', ".join(full_config.keys()) + "'")
NameError: Invalid filter name(s): 'Commands'

Related

Discord bot cannot fetch channel

I am trying to code a bot that will simultaneously print new messages in a server to console and for the user to be able to send messages to the server at the same time.
import discord
from asyncio import run
from threading import Thread
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
async def p():
ap = await client.fetch_channel(1234567890)
return ap
main_guild = run(p())
def log_msg(msge,date):
with open('log.txt','a') as f:
f.write(msge + '\n' + date)
f.close()
async def send_a_message():
while True:
await main_guild.send(input('Send message: '))
#client.event
async def on_message(message):
base_msg = str(message.author)+': '+str(message.channel.name)+': '+str(message.content)
date = str(message.created_at)
if len(message.attachments) == 0:
print(base_msg)
log_msg(base_msg,date)
return
for i in range(len(message.attachments)):
base_msg += '\n'+(message.attachments[i]).url
log_msg(base_msg,date)
t = Thread(target=lambda:run(send_a_message()))
t.start()
try:
client.run('#######################')
except discord.errors.HTTPException:
from os import system
system('kill 1')
However, I get a strange error:
Traceback (most recent call last):
File "main.py", line 13, in <module>
main_guild = run(p())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 10, in p
ap = await client.fetch_channel(999141783709679668)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/client.py", line 1824, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/http.py", line 604, in request
if not self._global_over.is_set():
AttributeError: '_MissingSentinel' object has no attribute 'is_set'
What is causing this and how do I fix this?
Thank you.
To get the channel you are using the client. But you are trying to get the channel before actually running the client, so you can't get the channel.
You have to first run the client and then get the channel. A possibility would be to use the on_ready event (called after client.run('...')) to get the channel.
Here is an example code you can start working with:
import discord
client = discord.Client(intents=discord.Intents.all())
main_guild = None
#client.event
async def on_ready():
global main_guild
await client.wait_until_ready()
main_guild = client.get_channel(1234567890)
print('Connected')
#client.event
async def on_message(message):
if message.author.id == client.user.id: return
if message.channel.type == discord.ChannelType.private: channel = 'DM'
else: channel = message.channel.name
base_msg = f'{message.author}: {channel}: {message.content}'
await main_guild.send(base_msg)
client.run('#######################')

Cannot add/append element to JSON File

So, I was making a discord bot for an RP server with 4k members in emergency.
My goal was to store the lawyers database in a json file that would be hosted on one of my computers for testing. Here is my code:
import discord
import datetime
from typing_extensions import IntVar
from discord import member
from discord.embeds import Embed
import json
from discord.ext import commands
from discord.colour import Color
import asyncio
#Vars
lawyersdict = {}
prefix = "<"
client = commands.Bot(command_prefix=prefix)
#Misc Stuff
client.remove_command("help")
#Embeds-
#RegEmbed
regembed = discord.Embed (
colour = discord.colour.Color.from_rgb(64, 255, 0),
title = 'Success',
description = 'Successfully registered you in the database as a lawyer!'
)
regembed.set_author(name='GVRP. Co',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
regembed.timestamp = datetime.datetime.utcnow()
#Invalid
factembed = discord.Embed (
colour = discord.colour.Color.from_rgb(255, 64, 0),
title = 'Uh oh',
description = 'Seems like an error occured! Please try again.'
)
factembed.set_author(name='UselessFacts',
icon_url='https://cdn.discordapp.com/avatars/921176863156609094/51441aaab15838c9a76c0488fd4ee281.webp?size=80')
factembed.timestamp = datetime.datetime.utcnow()
#CMDS-
#Register Command
#client.command(aliases=['reg'])
async def register(ctx):
if ctx.author == client.user:
return
else:
if isinstance(ctx.channel, discord.channel.DMChannel):
await ctx.send("Sorry, you cannot use this command in a DM for security reasons.")
else:
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
await channel.send(f"Hello {ctx.author.mention}! Please tell a little bit about yourself! You have 5 minutes. (To cancel the command, type 'cancel')")
await asyncio.sleep(0.3)
descmsg = await client.wait_for('message', check=check, timeout=300)
if descmsg.content == "cancel":
await channel.send(f"Cancelled command!")
else:
await channel.send(f"Almost there! You just need to enter the hiring price! You have 2 minutes. (between 450$ & 50,000$)")
await asyncio.sleep(0.3)
pricemsg = await client.wait_for('message', check=check, timeout=180)
if any(c.isalpha() for c in pricemsg.content):
if any(c.isalpha() for c in pricemsg.content):
await channel.send("Oops, you didnt typed a number! Make sure you didnt typed it without a coma! Please re-send the command.")
else:
def PrcCheck(num: int):
if num <= 50000 and num >= 450:
return True
else:
return False
if PrcCheck(int(pricemsg.content)):
desc = {
f"{str(ctx.author.id)}" : {
"Description" : f"{descmsg.content}",
"Price" : int(pricemsg.content),
"IsActive" : "true"
}
}
jsonobj = json.dumps(desc, indent=4, sort_keys= True)
with open('lawyers.json', mode='w') as outfile:
obj = json.load(json.dump(lawyersdict, outfile))
obj.append(desc)
obj.write(jsonobj, outfile)
await channel.send(embed=regembed)
else:
await channel.send(f"The price you entered is too low or too high! Price entered: ``{pricemsg.content}``. Please re-send the command.")
#client.event
async def on_ready():
print(f"Ready! Logged in as {client.user}")
client.run("Bot Token")
Here is the Compiler Error (Python 3.9):
Ignoring exception in command register:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\theli\OneDrive\Bureau\Discord Bots\GVRP. Co UtilBot\launcher.py", line 82, in register
obj = json.load(json.dump(lawyersdict, outfile))
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\theli\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'read'
I tried to look at other posts to see if there was a solution. But it was a post from 2015 which didn't solve my problem.
My goal here was to append details about the Discord User who entered the info and has entered my command to register.
Thank you for reading this post
obj = json.load(json.dump(lawyersdict, outfile))
You're using the result of json.dump() as the argument to json.load().
But json.dump() doesn't return anything. So you're effectively calling json.load(None).
As John Gordon said above dump return None therefore you cant load it .
To continue your comment, then yes json.load(outfile) is what you need to do but only later.
the file is open for w (write) and its currently an open file, so you can do it right away but after the with statement, by creating another io open call using the with context or with just an open.

Amino spam bot gives an error on login (python)

I'm not good at programming, so I took the code from the github, but after entering the password and email, an error pops up
Code
import amino
import asyncio
import pyfiglet
from colorama import init, Fore, Back, Style
init()
print(Fore.CYAN)
print("""Script by Lil Zevi
Github : https://github.com/LilZevi""")
print(pyfiglet.figlet_format("aminowallspam", font="stop"))
async def main():
client = amino.Client()
email = input("Email >> ")
password = input("Password >> ")
await client.login(email=email, password=password)
clients = await client.sub_clients(start=0, size=100)
for x, name in enumerate(clients.name, 1):
print(f"{x}.{name}")
communityid = clients.comId[int(input("Select the community >> "))-1]
sub_client = await amino.SubClient(comId=communityid, profile=client.profile)
userlink = input("User Link >> ")
user_info = await client.get_from_code(userlink)
userId = user_info.objectId
comment = input("Message >> ")
while True:
try:
await sub_client.comment(message=comment, userId=userId)
print("WallComment Sended")
except:
pass
asyncio.get_event_loop().run_until_complete(main())
Error
Traceback (most recent call last):
File "D:\py\am\am.py", line 32, in <module>
asyncio.get_event_loop().run_until_complete(main())
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "D:\py\am\am.py", line 15, in main
await client.login(email=email, password=password)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amino\client.py", line 210, in login
if response.status != 200: return exceptions.CheckException(json.loads(await response.text()))
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amino\lib\util\exceptions.py", line 855, in CheckException
elif api_code == 103 or api_code == 104: raise InvalidRequest(data)
amino.lib.util.exceptions.InvalidRequest: {'api:duration': '0.009s', 'api:message': 'Invalid Request. Please update to the latest version. If the problem continues, please contact us.', 'api:timestamp': '2021-08-23T13:27:25Z', 'api:statuscode': 104}
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000288650D4910>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x00000288650D78E0>, 456619.406)]']
connector: <aiohttp.connector.TCPConnector object at 0x00000288650D4940>

Grpc: TypeError: 'UnaryStreamCall' object is not iterable

Python code:
import asyncio
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
async def run() -> None:
async with grpc.aio.insecure_channel('localhost:50051') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
it = stub.FindNode(helloworld_pb2.FindNodeRequest())
for r in it:
print(r)
if __name__ == '__main__':
logging.basicConfig()
asyncio.run(run())
Protobuf:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
rpc FindNode(FindNodeRequest) returns (stream FindNodeReply) {}
}
message FindNodeRequest {
string target=1;
string from=2;
}
message FindNodeReply {
}
Error:
Traceback (most recent call last):
File "/Users/me/kad/client.py", line 26, in <module>
asyncio.run(run())
File "/usr/local/Cellar/python#3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/Cellar/python#3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/me/kad/client.py", line 17, in run
for r in it:
TypeError: 'UnaryStreamCall' object is not iterable
How do I fix this?
Fixed.
async for r in stub.FindNode(helloworld_pb2.FindNodeRequest()):
print(r)

Python MQTT to publish multiple message with same topic

I am trying to publish a multiple random data using mqtt to the broker. Below is the script for the publish part.
import paho.mqtt.client as mqtt
import json, schedule, time, random
client = mqtt.Client()
client.connect("<broker address", 1883, 60)
def pub_message():
tempreading = random.uniform(0, 100)
pHreading = random.uniform(1,14)
oxyreading = random.uniform(0, 100)
data_string1 = str(oxyreading)
data_string2 = str(pHreading)
data_string3 = str(tempreading)
msgs = [("randomdata", data_string1),("randomdata", data_string2),("randomdata", data_string3)]
client.publish(msgs)
schedule.every(1).minutes.do(pub_message)
while True:
schedule.run_pending()
time.sleep(1)
client.disconnect()
I ran the script and there is error like below:
Traceback (most recent call last):
File "mqttpub.py", line 27, in <module>
schedule.run_pending()
File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 462, in run_pending
default_scheduler.run_pending()
File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 75, in run_pending
self._run_job(job)
File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 129, in _run_job
ret = job.run()
File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 377, in run
ret = self.job_func()
File "mqttpub.py", line 22, in pub_message
client.publish(msgs)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 980, in publish
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False, info)
File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1979, in _send_publish
utopic = topic.encode('utf-8')
AttributeError: 'list' object has no attribute 'encode'
I searched about the publish multiple message with mqtt but did not find any good reference. I also included my mqtt subscribe part for receiving the multiple messages. I did search about this part too but did not find any good reference.
import paho.mqtt.client as mqtt
from models import *
from sqlalchemy.orm import sessionmaker
import json
def on_connect(client, userdata, rc):
print("connected with result code" + str(rc))
client.subscribe("randomdata")
def on_message(client, userdata, msg):
print "Topic:", msg.topic + " " + "Message:" + " " + "Value1:" + str(msg.payload1) + " " + "Value2:" + str(msg.payload2) + " " + "Value3:" + str(msg.payload3)
engine = create_engine('postgresql://user:password#localhost/mydatabase')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# store message received into database
raw_data = _Data(Value1=msg.payload1, Value2=msg.payload2, Value3=msg.payload3, time=msg.timestamp)
session.add(raw_data)
session.commit()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("<broker address>",1883, 60)
client.loop_forever()
Does anyone have any experience doing it? Thank you in advance.
What makes you think client.publish() will accept an array?
The doc's (https://pypi.python.org/pypi/paho-mqtt/1.1#publishing) don't mention anything about publishing multiple messages, you will have to call client.publish() once for every message you want to send.
You should also be calling client.loop() in your while true loop.
while True:
schedule.run_pending()
client.loop()
time.sleep(1)

Categories

Resources