I'm developing a telegram bot to register user and save his data in db. And after the registration I can't see that data in sqlite3. I don't understand what`s the problem and how to fix it
async def db_start():
global db, cur
db = sq.connect('base.db')
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS members(user_id TEXT PRIMARY KEY, name TEXT, phone TEXT, email TEXT, about TEXT, post TEXT, letters TEXT, box TEXT, donate TEXT)")
db.commit()
async def register(user_id):
user = cur.execute("SELECT 1 FROM members WHERE user_id == '{key}'".format(key=user_id)).fetchone()
if not user:
cur.execute("INSERT INTO members VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", (user_id, '', '', '', '', '', '', '', ''))
db.commit()
async def update(state, user_id):
async with state.proxy() as data:
cur.execute("UPDATE members SET name = '{}', phone = '{}', email = '{}', about = '{}', post = '{}', letters = '{}', box = '{}', donate = '{}' WHERE user_id == '{}'".format(data['name'], data['phone'], data['email'], data['about'], data['post'], data['letters'], data['box'], data['donate'], user_id))
db.commit()
Here is the db screens
db screen from sqlite3 db screen from pycharm
code from the main file
async def on_startup(_):
await db_start()
storage = MemoryStorage()
bot = Bot(token=config.TOKEN)
dp = Dispatcher(bot, storage=storage)
class ProfileStatesGroup(StatesGroup):
name = State()
phone = State()
email = State()
about = State()
post = State()
letters = State()
box = State()
donate = State()
def get_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/register'))
return kb
def get_cancel_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/cancel'))
return kb
#dp.message_handler(commands=['cancel'], state='*')
async def cmd_cancel(message: types.Message, state: FSMContext):
if state is None:
return
await state.finish()
await message.reply('text',
reply_markup=get_kb())
#dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message) -> None:
await message.answer("text", reply_markup=get_kb())
await register(user_id=message.from_user.id)
#dp.message_handler(commands=['register'])
async def cmd_create(message: types.Message) -> None:
await message.reply("text",
reply_markup=get_cancel_kb())
await ProfileStatesGroup.next()
# await ProfileStatesGroup.name.set()
#dp.message_handler(state=ProfileStatesGroup.name)
async def load_name(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['name'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.phone)
async def load_phone(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['phone'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.email)
async def load_email(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['email'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.about)
async def load_about(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['about'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.post)
async def load_post(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['post'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.letters)
async def load_letters(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['letters'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.box)
async def load_box(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['box'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.donate)
async def load_donate(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['donate'] = message.text
await update(state, user_id=message.from_user.id)
await message.reply("text")
await state.finish()
I will be very grateful if somebody helps me to find my problem :)
Related
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ?
Also seems like i need to post more details, don't pay attention to this :
Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
I'm getting POST http://localhost:8000/api/reports/ 415 (Unsupported Media Type) when I try to submit the form from React and I don't understand what's the problem.
Here's the code.
models.py
class Report(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
description = models.TextField()
address = models.CharField(max_length=500)
reporter_first_name = models.CharField(max_length=250)
reporter_last_name = models.CharField(max_length=250)
reporter_email = models.CharField(max_length=250)
reporter_phone = models.CharField(max_length=250)
report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
date = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ('-date',)
def __str__(self):
return self.description
I also tried to put default values for images, but I still get the error.
serializers.py
class ReportSerializer(serializers.ModelSerializer):
categoryName = CategorySerializer(many=False, read_only=True, source='category')
class Meta:
model = Report
fields = '__all__'
views.py
class ManageReports(viewsets.ModelViewSet):
serializer_class = ReportSerializer
parser_classes = [MultiPartParser, FormParser]
def get_object(self, queryset=None, **kwargs):
id = self.kwargs.get('pk')
return get_object_or_404(Report, id=id)
def get_queryset(self):
return Report.objects.all()
This is the code responsible for the submit.
report.js
const initialPostData = Object.freeze({
category: '',
address: '',
description: '',
reporter_first_name: '',
reporter_last_name: '',
reporter_email: '',
reporter_phone: '',
});
const [postData, updatePostData] = useState(initialPostData);
const [postImage1, setPostImage1] = useState({image: null});
const [postImage2, setPostImage2] = useState({image: null});
const [postImage3, setPostImage3] = useState({image: null});
const handleChange = (e) => {
if([e.target.name] == 'reporter_image_1') {
setPostImage1({
image: e.target.files[0],
});
} else if([e.target.name] == 'reporter_image_2') {
setPostImage2({
image: e.target.files[0],
});
} else if([e.target.name] == 'reporter_image_3') {
setPostImage3({
image: e.target.files[0],
});
} else if([e.target.name] == 'category') {
updatePostData({
...postData,
[e.target.name]: e.target.value,
});
} else {
updatePostData({
...postData,
[e.target.name]: e.target.value.trim(),
});
}
};
const handleSubmit = async(e) => {
e.preventDefault();
let formData = new FormData();
formData.append('category', postData.category);
formData.append('address', postData.address);
formData.append('description', postData.description);
formData.append('reporter_first_name', postData.reporter_first_name);
formData.append('reporter_last_name', postData.reporter_last_name);
formData.append('reporter_email', postData.reporter_email);
formData.append('reporter_image_1', postImage1.image);
formData.append('reporter_image_2', postImage2.image);
formData.append('reporter_image_3', postImage3.image);
const submitForm = await submitReport(formData);
And here's the submitReport API
API.js
const axiosInstance = axios.create({
baseURL: 'http://localhost:8000/api/',
timeout: 5000,
headers: {
Authorization: accessToken
? 'JWT ' + accessToken
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', {...formData });
return data;
}
These should be all the files needed to understand what's going on.
Thanks in advance.
Your parser_classes attribute on viewset is wrong. If you want to accept JSON format in request body you need to include JSONParser in your parser_classes attribute.
See the related section from here in DRF docs.
I found the solution, I was using the spread operator in the submitReport function, but instead I don't need to use it, so:
API.js
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', {...formData });
return data;
}
becomes
// Submit Report Form
const submitReport = async(formData) => {
const { data } = await axiosInstance.post('reports/', formData);
return data;
}
I have code like this:
#bot.command(pass_context=True)
#commands.has_any_role(admin, moderator, ghostluko)
async def ver(ctx,member:discord.Member = None):
role = ctx.guild.get_role(role_id=868210259284619324)
role1 = ctx.guild.get_role(role_id=905358001270046770)
await ctx.message.delete()
await member.add_roles(role)
await member.remove_roles(role1)
await ctx.send(f'{member} дал роль "{role}"')
after I add this, other commands start do not work
#bot.event
async def on_message(message):
embedbotreply = discord.Embed(description = f"Напишите help для подробной информации. Ваш префикс: {bot.command_prefix}", color = 0x8147fc)
if bot.user.mentioned_in(message):
await message.channel.send(embed = embedbotreply)
#bot.command()
async def ping(ctx):
embedping = discord.Embed(description = f" Мой пинг: {format(round(bot.latency, 1))} ms!", color = 0x8147fc)
await ctx.send(embed = embedping)
await ctx.message.delete()
Also, on_member_join do not work. I don't know what to do.
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
Try using await bot.process_commands(message) in your code and after this code you can use your other commands :
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
Hope, this helps you !!
i am getting an error when submiting Credit Card information Saying ("AttributeError at /API/CheckOut/" sources) i think it's comming from here but i don't know what the problem is
views.py
class PaymentView(APIView):
def post(self, request, *args, **kwargs):
order = Order.objects.get(user=self.request.user, ordered=False)
userprofile = UserProfile.objects.get(user=self.request.user)
token = request.data.get('stripeToken')
if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None:
customer = stripe.Customer.retrieve(
userprofile.stripe_customer_id)
customer.sources.create(source=token)
else:
customer = stripe.Customer.create(
email=self.request.user.email,
)
customer.sources.create(source=token)
userprofile.stripe_customer_id = customer['id']
userprofile.one_click_purchasing = True
userprofile.save()
i am using React on the frontend and Posting the Token like this
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});
const stoken=paymentMethod.id
if (error) {
seterror(error)
setloading(false);
} else {
seterror(null)
axios
.post(checkoutURL, {
stoken,
selectedBillingAddress,
selectedShippingAddress
})
so, im trying to make a reaction help with this code
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction == '➡️':
await ctx.send("NEEXT!")
return
elif reaction == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")
but when a reaction added, it dosen't do anything. Can someone help me? I want reaction help for 1week.
You need to use reaction.emoji when comparing to unicode emojis.
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '➡️':
await ctx.send("NEEXT!")
return
elif reaction.emoji == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")