problem finishing coding my python script using asyncio - python

I'm new to python and coding in general
here the code:
def job():
try:
users = sub_client.get_all_users(size=1)
except json.decoder.JSONDecodeError:
pass
for uid in users.profile.id:
with open("uid.txt", "r") as file:
uids = file.read().split("\n")[:-1]
if uid in uids:
print("already done")
else:
print("done")
sub_client.comment(userId=uid, message="welcome")
print(uid)
with open("uid.txt", "a") as f:
f.write(f"{uid}\n")
f.close()
while True:
readChat = ['4044f0f7-7963-46ad-b453-bb7d417be19a']
for chat in readChat:
messageList = sub_client.get_chat_messages(size=1, chatId=chat)
chatInfo = sub_client.get_chat_thread(chatId=chat)
for nickname, content, id in zip(messageList.author.nickname, messageList.content, messageList.messageId):
print(nickname, content)
content = str(content).split(" ")
if content[0][0] == "!":
if content[0][1:].lower() == "start":
sub_client.send_message(message="🤖 | ok! bot activé",chatId=chatInfo.chatId)
asyncio.create_task(job())
if content[0][1:].lower() == "stop":
sub_client.send_message(message="🤖 | ok! bot désactivé", chatId=chatInfo.chatId)
break
Would like that the first "job" run all the time when someone write "!start" into a chat, and that the task stop when someone write "!stop" (but not completly stopped, for example if someone write "!start" again into the chat, it restart the task, etc...)
Is this even possible?
The script will run 24/24, 7/7

Related

Discord.py Anti-spam ignore channel command broken

Hello I am trying to make an ANTI SPAM bot to work on catching spammers and kicking the from the server. My problem though with the code is that it ignores all channels in the guild and not the channels in the json file.
Here is my code can you please take a look and update me on what I did wrong. Thanks
#client.listen()
async def on_message(message):
counter = 0
with open("spam-bank.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
try:
with open("channels.json", "r") as r:
j = json.load(r)
all_channels = j["channels"]
return all_channels
if counter > 3:
await message.channel.send(f'{message.author} has been kicked for spamming')
await message.guild.kick(message.author,reason="Caught by Anti-Spam for Spamming")
print(f'{message.author} was kicked')
await asyncio.sleep(2)
except:
return
#client.command()
async def ignore(ctx, channel_):
def add_channel(channel, file="channels.json"):
with open(file, "r+") as fw:
j = json.load(fw)
j["channels"].append(channel)
with open(file, "w+") as wp:
wp.write(json.dumps(j))
try:
with open("channels.json", "r"):
pass
except:
with open("channels.json", "w+") as wp:
wp.write('{"channels" : []}')
finally:
add_channel(channel_)
await ctx.send("Done!")
The issue is here:
with open("channels.json", "r") as r:
j = json.load(r)
all_channels = j["channels"]
return all_channels
When execution hits return all_channels, the function ends, and all_channels is returned. No code after that will be reached.
Instead, you need to write code to check if the channel the message was sent in is contained in all_channels and return/skip only in that case.
One simple way to figure this out in the future is to add lots of temporary print statements, and trace through the function by following the print statements.
with open("channels.json", "r") as r:
j = json.load(r)
print("loaded json from file")
all_channels = j["channels"]
print(f"extracted channels from json: {all_channels}")
return all_channels
print(f"checking counter: {counter}")
if counter > 3:
print("user has sent more than 3 messages. Kicking..")
await message.channel.send(f'{message.author} has been kicked for spamming')
await message.guild.kick(message.author,reason="Caught by Anti-Spam for Spamming")
print(f'{message.author} was kicked')
await asyncio.sleep(2)
You'll get an output like
loaded json from file
extracted channels from json: [list]
And from that, you can easily tell that something's going wrong between that print statement and the next one, because checking counter: [number] isn't getting printed.

How can I run a Python package that uses asyncio in the background of another program?

I have looked all over this website for an answer but I can't find one. I am using ble-serial (https://github.com/Jakeler/ble-serial) to communicate with a heart rate monitor and send the data to a website. When I run the command to initialize BLE communication in the command prompt and then execute my website and data fetching code in my editor separately, it works fine. However, if I run the ble-serial package from my editor in the same program as the rest of my code, the website part never runs. I want to know how I can change my code to work the same as the first situation I described.
ser = serial.Serial("COM9",115200,8,'N',1)
ser.timeout = None
ser.is_open
sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)
pauseUpdates = True
timeOffset = 0
async def index(request):
with open('index2.html') as f:
return web.Response(text=f.read(), content_type='text/html')
app.router.add_get('/', index)
# Listens for messages from the website.
#sio.event
def s_PauseUpdates(sid, isPaused):
global pauseUpdates
pauseUpdates = isPaused
##sio.event
#def s_SetTimeZone(sid, timezone):
#global timeOffset
#timeOffset = int(timezone)
# loop that sends messages to the website
async def send_data_to_webclient():
#while True:
#if not pauseUpdates:
#timenow = datetime.utcnow()
#time = datetime(
#year=timenow.hour,
#month=timenow.month,
#day=timenow.day,
#hour=mod(timenow.hour + timeOffset, 24),
#minute=timenow.minute,
#second=timenow.second )
#await sio.emit('c_UpdateData', time.strftime("%H:%M:%S"))
#await sio.sleep(1)
hr = get_hr_only(ser)
for i in hr:
try:
if pauseUpdates:
send_command(ser, "pause 0\n")
await sio.emit('c_UpdateData', i[2])
else:
send_command(ser, "pause 1\n")
await sio.sleep(1)
except IndexError:
continue
async def init_app():
sio.start_background_task(send_data_to_webclient)
return app
if __name__ == '__main__':
address = input("Type in the device's SN-MAC address: ")
os.system(f'cmd /c "ble-serial -v -d {address} -w 00001027-1212-efde-1523-785feabcd123 -r 00001011-1212-efde-1523-785feabcd123" &')
clear_buffers(ser)
set_stream(ser)
web.run_app(init_app())

How can I remove the additional text that is written twice in my server-client chat?

Every time when I write something else, it shows me the first sentence I already wrote in addition to the new content.
def accept_client():
while True:
cli_sock, cli_add = ser_sock.accept()
uname = cli_sock.recv(1024)
name,message=uname.split(">")
CONNECTION_LIST.append((uname, cli_sock))
print('%s is now connected' %name)
thread_client = threading.Thread(target = broadcast_usr, args=[uname, cli_sock])
thread_client.start()
#this is my code from the server of the chat...

Whats the different about try: and def?

I'm trying to Open a file as text, choosing the file via str(raw_input, but it doesn't work with def main():.
My second script, with normal (No threading), is using try:. The threading one not opening the email.
Here is a link to the scripts in ghostbin:
Normal Script Without Threading and Multithread Script ,
The Normal Script Without Threading
try:
filelist = str(raw_input("[+] Enter Mailist File: "))
loglive = open('live.txt','a')
logdie = open('die.txt','a')
logun = open('uncheck.txt','a')
except Exception as Err:
print("ERROR : File List Not Found!")
sys.exit()
list = open(filelist, "r")
while True:
email = list.readline().replace("\n","")
if not email:
break
Multithread Script
def main():
start_time = time.time()
tanya = str(raw_input("[+] Enter Mailist File: "))
mailist = open(tanya, 'r')
while True:
email = mailist.readline().replace("\n","")
if not email:
break
s = requests.session()
You need to call the main function for it to be executed. At the end of your file, add:
if __name__ == '__main__':
main()
The reason for this can be found here: What does if __name__ == "__main__": do?

How to Read a txt File Based On Where a Specific character is

I Have a code that reads a file and randomly chooses a line from that file and sends it through DMs as a discord bot. However, I want it to read a certain section of the txt file by which character the section starts and ends with.
Ex: ,
Hi
,
This is the code I'm using that reads a random line and sends it through DM:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
emails = []
for email in emailFile:
emails.append(email)
#bot.command(pass_context = True)
#commands.cooldown(1, 30, commands.BucketType.user)
#commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = emails
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
Here's My Revision:
emailFile = open("C:/Users/jacob/Downloads/Uplay_Formatted.txt", "r",
encoding="utf16").read()
parse = False
email = []
for com in emailFile.split('\n'):
if com.startswith(',Credentials'):
parse = True
elif com.startswith(',Credentials'):
parse = False
if parse:
email.append(com)
#bot.command(pass_context = True)
#commands.cooldown(1, 30, commands.BucketType.user)
#commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = email
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen
To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30
Seconds Before Using This Command Again. If you do not wait the full
time then you won't be sent an alt.")
You can also use startswith() and endswith() example here
For example, in your case; it would be something along these lines:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
read_emails = emailFile.read()
emails = [com for com in read_emails.split() if com.startswith(',') and com.endswith(',')]
Per your requirements to display content between start and end. Try this:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r", encoding="utf8").read()
parse = False
for com in emailFile.split('\n'):
if com.startswith(',Credentials'):
parse = True
elif com.startswith(',Credentials'):
parse = False
if parse:
#do stuff
And if you are just trying to get the email addresses from the text file.
import re
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r", encoding="utf8").read()
email = []
for com in emailFile.split():
if re.match(r'[\w\.-]+#[\w\.-]+', com):
email.append(com)
Try using regex https://docs.python.org/2/library/re.html
You can match lines that start with the word 'Hi' re.match('^Hi', line)
The ^ indicates the start of the line, and theres a few other special characters that might help.

Categories

Resources