Skip to content

Commit 1137f82

Browse files
committed
fix: webhook bug
1 parent e837165 commit 1137f82

File tree

4 files changed

+139
-101
lines changed

4 files changed

+139
-101
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -512,4 +512,5 @@ MigrationBackup/
512512

513513
package-lock.json
514514
.DS_Store
515-
Thumbs.db
515+
Thumbs.db
516+
.vercel

api/webhook.js

Lines changed: 128 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -37,108 +37,141 @@ export default async function handler(req, res) {
3737
let responseMsg = '';
3838

3939
try {
40-
if (msg.location) {
40+
if (msg && msg.location) {
4141
const messageDate = new Date(msg.date * 1000);
42-
const hours = messageDate.toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul', hour12: false, hour: 'numeric' });
43-
const isWorkHour = hours >= 9 && hours < 18;
44-
const isWeekend = messageDate.getDay() === 0 || messageDate.getDay() === 6;
45-
const isHoliday = isPublicHoliday(messageDate);
46-
const willGoToDb = isWorkHour && !isWeekend && !isHoliday;
47-
const useCollectApi = process.env.USE_COLLECT_API === 'true';
48-
49-
await sendMessage(chatId, 'Konum bilgisi sorgulanıyor.');
50-
let locationSuccess = false;
51-
const latitude = msg.location.latitude;
52-
const longitude = msg.location.longitude;
42+
const hours = messageDate.toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul', hour12: false, hour: 'numeric' });
43+
44+
const isWorkHour = hours >= 9 && hours < 18;
45+
const isWeekend = messageDate.getDay() === 0 || messageDate.getDay() === 6;
46+
const isHoliday = isPublicHoliday(messageDate);
47+
const willGoToDb = isWorkHour && !isWeekend && !isHoliday;
48+
const useCollectApi = process.env.USE_COLLECT_API === 'true';
49+
50+
await sendMessage(chatId, 'Konum bilgisi sorgulanıyor.');
51+
let locationSuccess = false;
52+
53+
const latitude = msg.location.latitude;
54+
const longitude = msg.location.longitude;
5355

5456
try {
55-
const { country_code, city, district } = await getCityAndDistrictFromLocation(latitude, longitude);
56-
if (!country_code || country_code.toLowerCase() !== 'tr') {
57-
locationSuccess = true;
58-
responseMsg = 'Konumunuz Türkiye dışındaki bir ülke olarak tespit edildi. Servisimiz şu an için yalnızca Türkiye içerisindeki eczaneler için hizmet vermektedir. İlginiz için teşekkür ederiz.';
59-
} else if (city && district) {
60-
const userLocation = { latitude, longitude };
61-
let nearestPharmacies;
62-
async function getDataFromCollectApi() {
63-
nearestPharmacies = await fetchNearestPharmacies(city, district, userLocation);
64-
}
65-
if (willGoToDb) {
66-
nearestPharmacies = await findPharmaciesFromDb(city, district, userLocation);
67-
} else {
68-
if (useCollectApi) {
69-
await getDataFromCollectApi();
70-
} else {
71-
try {
72-
nearestPharmacies = await fetchPharmacies(city, district);
73-
} catch (error) {
74-
await getDataFromCollectApi();
75-
}
76-
}
77-
}
78-
if (nearestPharmacies && nearestPharmacies.length > 0) {
79-
if (willGoToDb) {
80-
await sendMessage(chatId, 'İlçenizdeki eczaneler listeleniyor.');
81-
} else {
82-
await sendMessage(chatId, 'Size en yakın olan nöbetçi eczaneler listeleniyor.');
83-
}
84-
const initialPharmacies = nearestPharmacies.slice(0, 5);
85-
for (let i = 0; i < initialPharmacies.length; i++) {
86-
const pharmacy = initialPharmacies[i];
87-
let pharmacyItemMsg = `Eczane adı: ${pharmacy.name}\nAdres: ${pharmacy.address}\nTelefon: ${pharmacy.phone}\n`;
88-
if (!pharmacy.googleMapsUrl || pharmacy.googleMapsUrl.length < 10) {
89-
const addressQuery = queryString.stringify({ query: pharmacy.address });
90-
pharmacy.googleMapsUrl = `${process.env.GOOGLE_MAPS_URI}&${addressQuery}`;
91-
}
92-
pharmacyItemMsg += `<a href=\"${pharmacy.googleMapsUrl}\">Haritada göster</a>`;
93-
await sendMessage(chatId, pharmacyItemMsg, { parse_mode: 'HTML' });
94-
}
95-
if (nearestPharmacies.length > 5) {
96-
await sendMessage(chatId, `${city}/${district} için toplam ${nearestPharmacies.length} eczane bulundu. Diğer eczaneleri görmek için "Daha Fazla Göster" butonuna tıklayın.`, {
97-
reply_markup: {
98-
inline_keyboard: [[{ text: 'Daha Fazla Göster', callback_data: 'show_more_pharmacies' }]]
57+
const { country_code, city, district } = await getCityAndDistrictFromLocation(latitude, longitude);
58+
if (!country_code || country_code.toLowerCase() !== 'tr') {
59+
locationSuccess = true;
60+
responseMsg = 'Konumunuz Türkiye dışındaki bir ülke olarak tespit edildi. Servisimiz şu an için yalnızca Türkiye içerisindeki eczaneler için hizmet vermektedir. İlginiz için teşekkür ederiz.';
9961
}
100-
});
101-
// Not: Vercel'de session yok, kalan eczaneleri bir veri tabanında veya başka bir yerde tutmak gerekir.
62+
else if (city && district) {
63+
console.log(`-> Request for: ${city} / ${district}`);
64+
65+
locationSuccess = true;
66+
67+
const userLocation = {
68+
latitude: msg.location.latitude,
69+
longitude: msg.location.longitude
70+
};
71+
72+
async function getDataFromCollectApi() {
73+
console.log(`-> Get CollectAPI - hours:${hours}, isWorkHour:${isWorkHour}, isWeekend:${isWeekend}, isHoliday:${isHoliday}`);
74+
nearestPharmacies = await fetchNearestPharmacies(city, district, userLocation);
75+
}
76+
77+
let nearestPharmacies;
78+
if (willGoToDb) {
79+
nearestPharmacies = await findPharmaciesFromDb(city, district, userLocation);
80+
} else {
81+
if (useCollectApi) {
82+
// Collect API
83+
await getDataFromCollectApi();
84+
} else {
85+
// MY API
86+
console.log(`-> Get MyAPI - hours:${hours}, isWorkHour:${isWorkHour}, isWeekend:${isWeekend}, isHoliday:${isHoliday}`);
87+
try {
88+
nearestPharmacies = await fetchPharmacies(city, district);
89+
} catch (error) {
90+
console.log(error);
91+
await getDataFromCollectApi();
92+
}
93+
}
94+
}
95+
96+
if (nearestPharmacies && nearestPharmacies.length > 0) {
97+
if (willGoToDb) {
98+
await sendMessage(chatId, 'İlçenizdeki eczaneler listeleniyor.');
99+
} else {
100+
await sendMessage(chatId, 'Size en yakın olan nöbetçi eczaneler listeleniyor.');
101+
}
102+
await new Promise(resolve => setTimeout(resolve, 200));
103+
const initialPharmacies = nearestPharmacies.slice(0, 5);
104+
for (let i = 0; i < initialPharmacies.length; i++) {
105+
const pharmacy = initialPharmacies[i];
106+
var pharmacyItemMsg = `Eczane adı: ${pharmacy.name}\nAdres: ${pharmacy.address}\nTelefon: ${pharmacy.phone}\n`;
107+
108+
if (pharmacy.googleMapsUrl === undefined || pharmacy.googleMapsUrl === null || pharmacy.googleMapsUrl.length < 10) {
109+
const addressQuery = queryString.stringify({ query: pharmacy.address });
110+
pharmacy.googleMapsUrl = `${process.env.GOOGLE_MAPS_URI}&${addressQuery}`;
111+
}
112+
113+
pharmacyItemMsg += `<a href="${pharmacy.googleMapsUrl}">Haritada göster</a>`;
114+
await sendMessage(chatId, pharmacyItemMsg, { parse_mode: 'HTML' });
115+
if (i < initialPharmacies.length - 1) {
116+
await new Promise(resolve => setTimeout(resolve, 500));
117+
}
118+
}
119+
if (nearestPharmacies.length > 5) {
120+
const remainingPharmacies = nearestPharmacies.slice(5);
121+
const latLonPairs = remainingPharmacies
122+
.map(p => `${p.location.lat}:${p.location.lon}`)
123+
.join(',');
124+
const encodedLatLons = Buffer.from(latLonPairs).toString('base64');
125+
126+
await sendMessage(chatId, `${city}/${district} için toplam ${nearestPharmacies.length} eczane bulundu. Diğer eczaneleri görmek için "Daha Fazla Göster" butonuna tıklayın.`, {
127+
reply_markup: {
128+
inline_keyboard: [[{ text: 'Daha Fazla Göster', callback_data: `show_more_pharmacies:${encodedLatLons}` }]]
129+
}
130+
});
131+
}
132+
} else {
133+
responseMsg = 'Yakınınızda eczane bulunamadı veya konum bilgisinde bir hata var.';
134+
}
135+
136+
try {
137+
if (process.env.MY_API_URI) {
138+
const rowData = {
139+
date: new Date().toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul' }),
140+
chatId,
141+
city,
142+
district
143+
};
144+
await appendUsageDataToGoogleSheets(rowData);
145+
}
146+
} catch (error) { }
147+
}
148+
} catch (error) {
149+
console.error('Hata oluştu:', error);
150+
responseMsg = 'Servislerde oluşan bir hatadan dolayı şu anda isteğinize yanıt alamadım. Konumu doğru gönderdiğinizden eminseniz tekrar deneyebilirsiniz.';
102151
}
103-
} else {
104-
responseMsg = 'Yakınınızda eczane bulunamadı veya konum bilgisinde bir hata var.';
105-
}
106-
try {
107-
if (process.env.MY_API_URI) {
108-
const rowData = {
109-
date: new Date().toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul' }),
110-
chatId,
111-
city,
112-
district
113-
};
114-
await appendUsageDataToGoogleSheets(rowData);
152+
153+
if (!locationSuccess) {
154+
responseMsg = 'Konum bilgisi alınamadı. Lütfen daha sonra tekrar deneyin.';
115155
}
116-
} catch (error) { }
156+
} else if (toLowerMessage === '/start' || toLowerMessage.includes('merhaba') || toLowerMessage.includes('selam')) {
157+
responseMsg = 'Hoş geldiniz!\n\nKonumunuzu bota gönderin ve size en yakın olan eczaneleri bulup göndersin.\n\nNot: Bilgileriniz hiçbir yerde kayıt edilmemektedir.';
158+
} else if (toLowerMessage === '/yardim' || toLowerMessage === '/help') {
159+
responseMsg = 'Bu bot konumunuza göre size en yakın eczane bilgilerini bulup göndermeye yarar. Bunun için mevcut konumunuzu bota göndermeniz yeterli. Konum bilginiz hiçbir yerde kayıt edilmemektedir.'
160+
} else if (toLowerMessage === '/developer') {
161+
responseMsg = 'Bu bot [Osman Koç](https://osmankoc.dev/) tarafından geliştirilmiştir.\n\nEğer bir sorun yaşıyorsanız veya öneriniz varsa [email protected] adresine mail olarak iletebilirsiniz.';
162+
} else if (toLowerMessage === '/contact') {
163+
responseMsg = 'Bir hata veya öneri bildirmek isterseniz [email protected] adresine mail gönderebilirsiniz. Şimdiden teşekkürler!'
164+
} else if (toLowerMessage === 'ping') {
165+
responseMsg = 'pong';
166+
} else if (toLowerMessage === 'test') {
167+
responseMsg = 'Sensin test :)';
168+
} else if (toLowerMessage.includes('naber') || toLowerMessage.includes('nasılsın')) {
169+
responseMsg = 'Size yardımcı olmakla meşgulüm. Ben bir chat botu değil, size yakın olan eczaneleri bulup iletmekle görevliyim. Bu nedenle bu tarz sorularınıza yanıt veremeyebilirim. İlginiz için teşekkür ederim.';
170+
}
171+
172+
if (responseMsg !== '') {
173+
await sendMessage(chatId, responseMsg, { parse_mode: 'HTML' });
117174
}
118-
} catch (error) {
119-
responseMsg = 'Servislerde oluşan bir hatadan dolayı şu anda isteğinize yanıt alamadım. Konumu doğru gönderdiğinizden eminseniz tekrar deneyebilirsiniz.';
120-
}
121-
if (!locationSuccess) {
122-
responseMsg = 'Konum bilgisi alınamadı. Lütfen daha sonra tekrar deneyin.';
123-
}
124-
} else if (toLowerMessage === '/start' || toLowerMessage.includes('merhaba') || toLowerMessage.includes('selam')) {
125-
responseMsg = 'Hoş geldiniz!\n\nKonumunuzu bota gönderin ve size en yakın olan eczaneleri bulup göndersin.\n\nNot: Bilgileriniz hiçbir yerde kayıt edilmemektedir.';
126-
} else if (toLowerMessage === '/yardim' || toLowerMessage === '/help') {
127-
responseMsg = 'Bu bot konumunuza göre size en yakın eczane bilgilerini bulup göndermeye yarar. Bunun için mevcut konumunuzu bota göndermeniz yeterli. Konum bilginiz hiçbir yerde kayıt edilmemektedir.';
128-
} else if (toLowerMessage === '/developer') {
129-
responseMsg = 'Bu bot [Osman Koç](https://osmankoc.dev/) tarafından geliştirilmiştir.\n\nEğer bir sorun yaşıyorsanız veya öneriniz varsa [email protected] adresine mail olarak iletebilirsiniz.';
130-
} else if (toLowerMessage === '/contact') {
131-
responseMsg = 'Bir hata veya öneri bildirmek isterseniz [email protected] adresine mail gönderebilirsiniz. Şimdiden teşekkürler!';
132-
} else if (toLowerMessage === 'ping') {
133-
responseMsg = 'pong';
134-
} else if (toLowerMessage === 'test') {
135-
responseMsg = 'Sensin test :)';
136-
} else if (toLowerMessage.includes('naber') || toLowerMessage.includes('nasılsın')) {
137-
responseMsg = 'Size yardımcı olmakla meşgulüm. Ben bir chat botu değil, size yakın olan eczaneleri bulup iletmekle görevliyim. Bu nedenle bu tarz sorularınıza yanıt veremeyebilirim. İlginiz için teşekkür ederim.';
138-
}
139-
if (responseMsg !== '') {
140-
await sendMessage(chatId, responseMsg, { parse_mode: 'HTML' });
141-
}
142175
} catch (error) {
143176
await sendMessage(chatId, 'Bir hata oluştu, lütfen tekrar deneyin.');
144177
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "enyakineczanebot",
3-
"version": "2.0.1",
3+
"version": "2.0.2",
44
"description": "Yakındaki veya nöbetçi eczaneleri sorgulamak için Telegram botu",
55
"type": "module",
66
"repository": {

services/my-api.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import 'dotenv/config';
22

33
async function fetchPharmacies(city, district) {
4-
const url = `${process.env.MY_API_URI}/pharmacies/${encodeURIComponent(city)}/${encodeURIComponent(district)}`;
4+
const url = `${process.env.MY_API_URI}/pharmacies?city=${encodeURIComponent(city)}&district=${encodeURIComponent(district)}`;
55

66
try {
77
const headers = {
@@ -13,13 +13,17 @@ async function fetchPharmacies(city, district) {
1313
const response = await fetch(url, {
1414
headers
1515
});
16+
const contentType = response.headers.get('content-type');
17+
if (!contentType || !contentType.includes('application/json')) {
18+
const text = await response.text();
19+
console.error('API non-JSON response:', text);
20+
throw new Error('API non-JSON response');
21+
}
1622
const data = await response.json();
17-
1823
if (!Array.isArray(data) || data.length === 0) {
19-
console.log(data);
24+
console.log('API response (empty or not array):', data);
2025
throw new Error('API request failed or no pharmacies found');
2126
}
22-
2327
return data;
2428
} catch (error) {
2529
console.error('Error fetching pharmacies:', error);

0 commit comments

Comments
 (0)